syscalls

setuid() — Linux system interface

Set user identity according to the calling process credentials. On Linux a caller with CAP_SETUID in its user namespace can set real, effective and saved IDs; an unprivileged caller can set the effective ID to its real or saved ID subject to rules. Always check errors even when privileged. EPERM indicates insufficient authority; EINVAL can indicate an unmapped UID. Credential drops need careful group, capability, saved-ID and thread review; this example is not a privilege-drop recipe. It only calls setuid with the existing real UID in an ordinary non-root process with equal real, effective and saved IDs. Never install it setuid-root or run with sudo. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. Linux-specific interface or flags; examples target Linux/glibc on x86_64. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#include <unistd.h>int setuid(uid_t uid);

Parameters & Attributes

NameTypeDescription
uiduid_tRequested numeric user ID; this example uses its existing UID.

Return Value

int

0 on success. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \    fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \    return EXIT_FAILURE; \} } while (0)
int main(void){    uid_t real, effective, saved;    CHECK(getresuid(&real, &effective, &saved) == 0);    CHECK(real != 0 && real == effective && real == saved);    CHECK(setuid(real) == 0);    uid_t r, e, s;    CHECK(getresuid(&r, &e, &s) == 0);    CHECK(r == real && e == effective && s == saved);    puts("same non-root UID accepted; credentials unchanged");    return EXIT_SUCCESS;}
Linux Reference