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...