gpt4 book ai didi

c - 使用 posix_spawn 设置 euid

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:26 28 4
gpt4 key购买 nike

我有以下代码片段。

char *const parmList[] = {"sh", "-c", "whoami", NULL};
if(geteuid() == 0) {
seteuid(atoi(getenv("SUDO_UID")));
}
posix_spawn(&pid, "/bin/sh", NULL, NULL, parmList, environ);

根据我的理解,posix_spawn 的默认行为是:

If the POSIX_SPAWN_RESETIDS flag is not set, the child process shall inherit the parent process' effective user ID.

但是,当我使用 sudo 运行我的程序时,我仍然得到 root 作为 posix_spawn 的输出。我怎样才能让 posix_spawn 以原始用户身份运行?有更好的方法吗?

最佳答案

我最终通过创建一个fork然后是exec

的函数来完成这个
pid_t runCmd(char *cmd) {
if(!cmd) return -1;

pid_t ans = fork();
if(ans == 0) {
if(geteuid() == 0) {
int uid = atoi(getenv("SUDO_UID"));
setreuid(uid, uid);
}
if(verbose_flag) println("uid %d; euid %d", getuid(), geteuid());
char *const parmList[] = {"sh", "-c", cmd, NULL};
execv("/bin/sh", parmList);
}
return ans;
}

whoami 现在返回原始用户

关于c - 使用 posix_spawn 设置 euid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40532401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com