Linux C编程以用户身份执行 [英] Linux C programming execute as user

查看:61
本文介绍了Linux C编程以用户身份执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以root身份运行的程序.我希望该程序以普通用户身份执行另一个应用程序.我尝试了 setgid(),它可以工作,但是我不能再回到root或其他用户的位置.暂时的程序很简单;

I have an program which I run as root. I would like the program to execute another application as a normal user. I tried setgid() and it works, but I can't then go back to root or another user. The program for the time being is very simple;

 #include <stdio.h>
 #include <unistd.h>
 #include <stdlib.h>

 int main(int argc, char *argv[] )
 {
     if ( argc != 2) {
         printf("usage: %s command\n",argv[0]);
         exit(1);
     }
     setgid(100);
     setuid(1000);
     putenv("HOME=/home/caroline");
     putenv("DISPLAY=:0");
     system(argv[1]);
     seteuid(1001);
     putenv("HOME=/home/john");
     putenv("DISPLAY=:1");
     system(argv[1]);
     return 0;
 }

我该怎么做?就像命令 su $ user-c $ command

How can I do this? It's like the action of command su $user-c $command

推荐答案

如果使用 fork + exec ,则可以更改子进程的 euid ,同时保持其根用户身份.父母.代码可能看起来像这样:

If you use fork+exec you can change euid of the child process while staying as root in the parent. The code could look something like this:

 #include <stdio.h>
 #include <unistd.h>
 #include <stdlib.h>

 int runAs(int gid, int uid, char **env, char *command) {
   int child = fork();
   if (child == 0) {
    setgid(100);
     setuid(1000);
     do {
       putenv(*env);
       env++;
     } while (env != null);
     exec(command);
   } else if (child > 0) {
    waitpid(child);
   } else {
     // Error: fork() failed!
   }
 }


 int main(int argc, char *argv[] )
 {
     char *env[3];
     if ( argc != 2) {
         printf("usage: %s command\n",argv[0]);
         exit(1);
     }
     env[0] = "HOME=/home/caroline";
     env[1] = "DISPLAY=:0";
     env[2] = NULL;
     runAs(100, 1000, env, argv[1]);

     env[0] = "HOME=/home/john";
     env[1] = "DISPLAY=:1";
     runAs(100, 1001, env, argv[1]);
     return 0;
 }

这篇关于Linux C编程以用户身份执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆