setuid() sets the effective user ID of the calling process. If the effective UID of the caller is root, the real UID and saved set-user-ID are also set.
Under Linux, setuid() is implemented like the POSIX version with the _POSIX_SAVED_IDS feature. This allows a set-user-ID (other than root) program to drop all of its user privileges, do some un-privi-leged work, and then re-engage the original effective user ID in a secure manner.
If the user is root or the program is set-user-ID-root, special care must be taken. The setuid() function checks the effective user ID of the caller and if it is the superuser, all process-related user ID's are set to uid. After this has occurred, it is impossible for the program to regain root privileges.
Thus, a set-user-ID-root program wishing to temporarily drop root privileges, assume the identity of a non-root user, and then regain root privileges afterwards cannot use setuid(). You can accomplish this with the (non-POSIX, BSD) call seteuid(2).
如果一个set-user-ID-root程序仅仅想暂时地放弃root权限,那么可以调用seteuid(non-root-uid),这样之后如果想重新获取到root权限,调用seteuid(0)即可!!!这是因为,seteuid()只会改变进程的effective user ID。当调用seteuid(non-root-uid),这时effective user ID是变成了non-root-uid,但saved set-user-ID还是为0(即root),所以当再次调用seteuid(0)时,又能将effective user ID设置为root。
man seteuid
-----
seteuid() sets the effective user ID of the calling process. Unprivileged user processes may only set the effective user ID to the real user ID, the effective user ID or the saved set-user-ID.