← GCC/C Index

🐧 <unistd.h> — POSIX API — Process, Files, I/O (Linux/macOS only)

POSIX/Linux only — not available on Windows without WSL/Cygwin. Provides access to the OS: process IDs, file descriptors, fork/exec, and sleep.

Include: #include <unistd.h> | Compile: gcc -Wall -o prog prog.c

📋 Functions & Macros

NamePrototype / ValueDescription
readssize_t read(int fd, void *buf, size_t n)Read n bytes from file descriptor
writessize_t write(int fd, const void *buf, size_t n)Write n bytes to file descriptor
closeint close(int fd)Close a file descriptor
forkpid_t fork(void)Create a child process
getpidpid_t getpid(void)Return PID of current process
getppidpid_t getppid(void)Return PID of parent process
sleepunsigned sleep(unsigned secs)Sleep for secs seconds
usleepint usleep(useconds_t usecs)Sleep for microseconds
pipeint pipe(int fds[2])Create a pipe
dup2int dup2(int oldfd, int newfd)Duplicate file descriptor
chdirint chdir(const char *path)Change working directory
getcwdchar *getcwd(char *buf, size_t size)Get current working directory
unlinkint unlink(const char *path)Delete a file
accessint access(const char *path, int mode)Check file accessibility
getuiduid_t getuid(void)Return user ID

💡 Example Program

Copy, save as demo.c, and compile with the command shown at the bottom.

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    printf("Parent PID = %d\n", getpid());
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    else if (pid == 0) {
        printf("Child  PID = %d (parent=%d)\n", getpid(), getppid());
        sleep(1);
        printf("Child done.\n");
    } else {
        int status;
        waitpid(pid, &status, 0);
        printf("Parent: child exited with status %d\n", WEXITSTATUS(status));
    }
    return 0;
}
/* Compile (Linux/macOS): gcc -Wall -o fork_demo fork_demo.c */

← <signal.h>  |  🏠 Index