CodeBlanks Logo Icon CodeBlanks

Summary - Process management

Combine fork, exec and wait to write a shell.

The shell pattern

In this group you learned the three core tools of process management: create a process with fork, replace the program with exec, and wait with wait. Together they form the basis of UNIX shells.

Now you will combine them into a simple shell: fork a child, run the command with execvp in the child, and wait in the parent. This pattern runs behind every command-line shell.

Practice Mini shell

Create a child with pid_t pid = fork();. In the child, char *args[] = {"echo", "merhaba", NULL}; and execvp("echo", args);. In the parent, int status; wait(&status); and printf("bitti\n");.

Starter code

main.c
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

// Fork
// Child runs echo with execvp
// Parent wait and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {
        char *args[] = {"echo", "merhaba", NULL};
        execvp("echo", args);
        _exit(1);
    }
    int status;
    wait(&status);
    printf("bitti\n");
    return 0;
}

Expected output

merhaba
bitti

Next steps

You learned process management. In the next groups you will see inter-process communication with signals, concurrent work with threads, and network communication with sockets.

All these topics build on fork, exec and wait. For example, a server uses fork to create a child for each client. getpid and exit will appear everywhere for debugging and clean exit.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What sequence does a shell follow to run a command?

  • exec, fork, wait
  • wait, fork, exec
  • fork, wait, exec
  • fork, exec, wait Correct answer

Explanation: First fork, then exec in child, then wait in parent.

2 Match the shell steps

Term Meaning
fork Create process
execvp Run program
wait Wait for child
exit End process

All lessons in Advanced