我有一个以root用户身份运行的程序(getuid()
返回0)。
我需要执行一个命令行工具作为当前登录的用户(我可以通过getting the HOME env var确定)。 (详见下文)
我怎么做,理想情况下使用NSTask
?
我知道如何使用NSTask作为当前(root)用户来执行该工具,所以我需要的是知道我需要改变什么。
或者,有没有办法在不同用户的ID下运行我的程序代码的一部分?
精
特别是,该计划由AuthorizationExecuteWithPrivileges
发起。有趣的是,这使程序与使用sudo启动程序时的环境略有不同:
使用sudo,实际有效的用户(来自getuid()
和geteuid()
)都是“root”。
但是,使用AuthorizationExecuteWithPrivileges
,有效用户仍然是调用该函数的用户。这有一些奇怪的影响,例如:然后程序使用NSUserDefaults,因为它们最终出现在不同的域中,我的测试显示。
其他人建议使用fork
函数,然后在分叉进程中调用setuid
,然后再使用NSTask或system()运行外部命令。
以下是如何做到这一点:
int userID = 501; // or whatever user you need to be
assert (geteuid() == 0); // are we root?
pid_t pid;
if ((pid = fork()) == 0) {
setuid(userID);
int res = system("...");
exit (res);
} else {
// wait for the forked process to finish
pid_t endid;
do {
int status;
endid = waitpid (pid, &status, WNOHANG|WUNTRACED);
} while (endid == 0);
}