I have a program to run as root, and during execution this program will do a few things as different uers, so I wanted to use a serial of setuid()s. But, I found that, after setuid(user1), I become user1 and thus don't have the privilege to do setuid(user2).
How can I get back to root so that I can do setuid(user2)?
Thanks.
Use fork
, let the child setuid
and perform whatever actions that needs to be done as the second user. The root parent waits for the child and continues when the child has finished executing.
childpid = fork();
if (childpid < 0) {
// fork failed
}
if (childpid == 0) {
// Child
setuid(user1);
prepareUser1(); // Do some stuff as user1.
exit(0); // Done as user1
} else {
// parent: wait for child to finish
waitpid(childpid);
}
// Parent continues as root...