setuid()

Updated: April 19, 2023

Set the real, effective and saved user IDs

Synopsis:

#include <unistd.h>

int setuid( uid_t uid );

Arguments:

uid
The user ID that you want to use for the process.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

If the process has the PROCMGR_AID_SETUID ability for the supplied user ID, setuid() sets the real, effective, and saved set-user IDs to the value passed in.

If the process does not have the ability but the user ID matches that of the process's current real, effective, or saved set-user IDs, then only the effective user ID is set to the value passed in.

Due to the subtle behavior of setuid(), QNX recommends that you instead use setreuid() with both user IDs set to the same value unless it is intended that only the effective user ID be changed, in which case seteuid() should be used. It is recommended that you do not use a negative value for a user ID.

Returns:

0 for success, or -1 if an error occurs (errno is set).

Errors:

EINVAL
The value of uid is out of range.
EPERM
The process doesn't have the PROCMGR_AID_SETUID ability enabled, and uid doesn't match the real user ID or saved set-user ID.

Examples:

/*
 * This process sets its userid to 0 (root)
 */
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main( void )
{
    uid_t ouid;

    ouid = getuid();
    if( setuid( 0 ) == -1 ) {
        perror( "setuid" );
        return EXIT_FAILURE;
    }

    printf( "userid %d switched to 0\n", ouid );
    return EXIT_SUCCESS;
}

Classification:

POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes