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
| Name | Prototype / Value | Description |
|---|---|---|
| read | ssize_t read(int fd, void *buf, size_t n) | Read n bytes from file descriptor |
| write | ssize_t write(int fd, const void *buf, size_t n) | Write n bytes to file descriptor |
| close | int close(int fd) | Close a file descriptor |
| fork | pid_t fork(void) | Create a child process |
| getpid | pid_t getpid(void) | Return PID of current process |
| getppid | pid_t getppid(void) | Return PID of parent process |
| sleep | unsigned sleep(unsigned secs) | Sleep for secs seconds |
| usleep | int usleep(useconds_t usecs) | Sleep for microseconds |
| pipe | int pipe(int fds[2]) | Create a pipe |
| dup2 | int dup2(int oldfd, int newfd) | Duplicate file descriptor |
| chdir | int chdir(const char *path) | Change working directory |
| getcwd | char *getcwd(char *buf, size_t size) | Get current working directory |
| unlink | int unlink(const char *path) | Delete a file |
| access | int access(const char *path, int mode) | Check file accessibility |
| getuid | uid_t getuid(void) | Return user ID |
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 */