unix_system_calls_example
unix_system_calls_example
This document provides an example of a C program that utilizes several Unix system calls such as
fork, exec, getpid, exit, wait, close, opendir, and readdir. The program demonstrates how a parent
process can create a child process to list the contents of a directory, while the parent waits for the
child to complete.
Code Explanation:
4. readdir: Reads the next directory entry from the directory stream.
6. exec: Not used directly in this example but could replace the child process image with a new
program.
8. wait: Waits for the child process to change state, and retrieves its exit status.
9. status: Captures the exit status of the child process, used in conjunction with wait.
Sample Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
void list_directory(const char *path) {
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
printf("%s\n", entry->d_name);
if (closedir(dir) == -1) {
perror("closedir");
exit(EXIT_FAILURE);
int main() {
pid_t pid;
int status;
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
list_directory(".");
exit(EXIT_SUCCESS);
if (wait(&status) == -1) {
perror("wait");
exit(EXIT_FAILURE);
if (WIFEXITED(status)) {
} else {
return 0;