Elementary Operating System Calls & IPC Mechanisms
Idea in plain words
fork() creates an exact duplicate child process with separate memory address space; returns 0 in the child and child PID in parent.
Exam tip
High-yield exam topic (Very High).
Explanation
Operating systems execute concurrent server tasks by decoupling network listener loops from individual client sessions. When fork() is called, the kernel clones file descriptor tables, incrementing reference counts on open sockets. To avoid descriptor leaks, the parent process immediately closes the connected socket descriptor (connfd), while the child closes the listening socket descriptor (listenfd). When a child finishes, it becomes a 'zombie' until the parent calls wait() or waitpid(). Installing a signal handler for SIGCHLD prevents zombie accumulation in high-concurrency production daemons.
Key points
- exec() family (execl, execp, execv) replaces the current process image with a new executable file.
- wait() and waitpid() allow a parent process to collect child exit status and prevent zombie processes; waitpid with WNOHANG enables non-blocking checks.
- Inter-Process Communication (IPC): pipe() provides unidirectional byte streams between related processes; mkfifo() creates named pipes persistent in the filesystem.
- Signals (SIGCHLD, SIGINT, SIGIO): Asynchronous notifications from the kernel; SIGCHLD must be handled to reap terminated child servers.
Example
Example
Creating an IPC pipe: int fd[2]; pipe(fd); where fd[0] is the read end and fd[1] is the write end. Fifos (named pipes) created via mkfifo('/tmp/myfifo', 0666) allow unrelated processes to communicate.
Code examples
#include <signal.h>
#include <sys/wait.h>
void sig_chld(int signo) {
pid_t pid;
int stat;
// Non-blocking wait loop to reap all terminated children
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) {
// Child reaped cleanly
}
}
// In main():
signal(SIGCHLD, sig_chld);
Exam questions
- [10 Marks] Explain fork(), exec(), and waitpid() system calls. How does an asynchronous SIGCHLD signal handler prevent zombie processes?
- [5 Marks] Differentiate between anonymous pipes (pipe) and named pipes (FIFO) in Unix IPC.