C System Programming: POSIX System Calls, Processes & IPC Masterclass
Welcome to Phase 22 (Chapter 61): C System Programming โ POSIX System Calls, Processes & IPC Masterclass! System programming interacts directly with the operating system kernel. In this guide, you will master POSIX system calls, process creation with `fork()`, process replacement with `execvp()`, and Inter-Process Communication (IPC) via pipes.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(void) {
int pipefd[2]; // pipefd[0] = read, pipefd[1] = write
if (pipe(pipefd) == -1) { perror("pipe"); return 1; }
pid_t pid = fork();
if (pid < 0) { perror("fork"); return 1; }
if (pid == 0) { // CHILD PROCESS
close(pipefd[1]); // Close unused write end
char buffer[128];
ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer) - 1);
if (bytesRead > 0) {
buffer[bytesRead] = '\0';
printf("[Child Received]: %s\n", buffer);
}
close(pipefd[0]);
exit(0);
} else { // PARENT PROCESS
close(pipefd[0]); // Close unused read end
const char *msg = "Hello from Parent Process!";
write(pipefd[1], msg, strlen(msg));
close(pipefd[1]);
wait(NULL); // Wait for child to exit
printf("[Parent]: Child finished execution.\n");
}
return 0;
} Q1: What is a Zombie process in C?
A terminated child process whose parent has not yet called `wait()` or `waitpid()` to read its exit status, leaving an entry in the OS process table.
Q2: What is an Orphan process?
A child process whose parent process terminated before it. The OS `init` / `systemd` process (PID 1) automatically adopts orphans.
Q3: What is the difference between system() and execvp()?
`system()` launches a new shell subprocess. `execvp()` completely overwrites the current process memory image with the new binary.
Q4: How do file descriptors work in POSIX?
Integers indexing an OS kernel table: 0 is stdin, 1 is stdout, 2 is stderr. `open()` returns descriptor numbers 3, 4, 5...
Q5: What is signal handler safety in C?
Signal handlers interrupt normal program flow asynchronously. Only async-signal-safe functions (like `write()`) should be called inside signal handlers.