The programming interface
On this page
The system calls programs use to manage processes (fork, exec, wait, signal), do I/O (open, read, write, close) and talk to each other (pipe, dup). The shell ties them together.
Main points
- Creating and managing processes:
fork,exec,wait - Performing I/O:
open,read,write,close - Communicating between processes:
pipe,dup,select,connect - Example: implementing a shell
The shell
A shell is a job control system: it lets the user create and manage a set of programs to do some task. Windows, macOS and Linux all have one. Compiling a C program, for example, runs several programs in turn:
cc -c sourcefile1.c
cc -c sourcefile2.c
ln -o program sourcefile1.o sourcefile2.o
Since the shell runs at user level, it must use system calls to start each program.
Creating processes
Windows: CreateProcess
One system call that does everything:
- Create and initialise the process control block (PCB) in the kernel.
- Create and initialise a new address space.
- Load the program into the address space.
- Copy arguments into memory in the address space.
- Initialise the hardware context to start execution at “start”.
- Inform the scheduler that the new process is ready to run.
UNIX: fork, exec, wait, signal
fork- Create a copy of the current process and start it running. No arguments. Returns 0 in the child and the child's process ID in the parent (−1 on error).
exec- Change the program being run by the current process. Only returns if it fails.
wait- Wait for a child process to finish (block until the specified child has exited).
signal- Send a notification to another process.
Implementing fork: create and initialise the PCB; create a new address space; initialise it with a copy of the entire contents of the parent's address space; inherit the parent's execution context (for example open files); tell the scheduler the new process is ready.
Implementing exec: load the program into the current address space; copy the arguments into memory in the address space; initialise the hardware context to start at “start”.
So the main difference from Windows: fork() copies the parent's process image into the child, while CreateProcess reads the executable image from disk. In practice fork does not copy every page: see copy-on-write.
int child_pid = fork();
if (child_pid == 0) { // I'm the child process
printf("I am process #%d\n", getpid());
return 0;
} else { // I'm the parent process
printf("I am parent of process #%d\n", child_pid);
return 0;
}
Both lines print, from two different processes, in an order chosen by the scheduler.
Questions from the lecture
- Can fork return an error? Yes, for example when the process limit is reached.
- Can exec return an error? Yes, for example when the file doesn't exist. If it returns at all, it failed.
- Can wait return immediately? Yes, if the child has already finished.
Implementing a shell
char *prog, **args;
int child_pid;
// Read and parse the input a line at a time
while (readAndParseCmdLine(&prog, &args)) {
child_pid = fork(); // create a child process
if (child_pid == 0) {
exec(prog, args); // I'm the child process. Run program
// NOT REACHED
} else {
wait(child_pid); // I'm the parent, wait for child
}
}
The shell forks and then execs in the child because calling exec directly would replace the shell itself.
The course's shell exercise
- Print a prompt with
printf()orputs(). - Read input from stdin.
fork()a child process.- In the child, call
execve()with the file the user typed. - In the parent, call
wait(), which returns when the child exits. - Go back to step 1.
Two common pitfalls:
execveis the raw system call and needs a full path (/bin/ls, notls); otherwise it fails with “No such file or directory”.execvpandexeclpalso search$PATH.fgetskeeps the trailing newline, soexecvewon't find the file. Replace'\n'with'\0'first.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
char input[256];
while(1)
{
printf("shell> ");
fflush(0);
fgets(input, sizeof(input), stdin);
if(strlen(input) < 2)
continue;
input[strlen(input)-1] = '\0'; // Strip newline
int pid = fork();
if(pid == 0)
{
// Child
char *args[] = {input, NULL};
char *env[] = {NULL};
execve(input, args, env);
}
else
{
// Parent, wait
waitpid(pid, NULL, 0);
}
}
}
Extensions from the exercises: tokenise with strtok and call execvp(args[0], args); run jobs in the background with & (don't wait); redirect I/O with dup2 before execvp; build pipes with pipe and dup2; catch SIGINT in the shell but not in the children.
If the parent never calls wait, nobody collects the child's exit status, and the parent may finish first so the shell prompt gets mixed up with the child's output.
Fork bombs
A fork bomb is a process that keeps replicating itself to use up system resources (a denial-of-service attack):
void main()
{
while(1) fork();
}
Every child runs the same loop, so the number of processes grows exponentially and overwhelms memory and the process table. Since fork() is a system call, the OS can limit it: a maximum number of processes per user, which on Linux you can see with ulimit -u.
UNIX I/O
- Uniformity: all operations on all files and devices use the same calls:
open,close,read,write. - Open before use:
openreturns a handle, the file descriptor, used in later calls. - Byte-oriented.
- Kernel-buffered read and write.
- Explicit close, to garbage-collect the open file descriptor.
Every process starts with three descriptors: 0 (stdin), 1 (stdout) and 2 (stderr).
Why open is a Swiss Army knife
UNIX open takes options: return an error if the file doesn't exist, or create it; return an error if it already exists, or open it; truncate it if it isn't empty, and so on. Why not separate calls?
if (!exists(name))
create(name); // can create fail?
fd = open(name); // does the file exist?
Between each call, another process could create or delete the file. Combining them into one system call makes the check-and-act atomic.
Strace: watching the kernel
The exercises use strace to see the system calls behind library functions:
strace -e trace=clone,execve,wait4 ./forkexec
strace -c ./fileread_multi big.bin syscalls sequential > /dev/null
On Linux, fork and pthread_create both show up as clone; see threads.
On earlier exams
- 2023, question 8 – Mode switch
- 2023, question 9 – Fork bomb
- 2023, question 20 – File descriptor
- 2024, question 21 – Process abstraction
- 2024, question 22 – Writing numbers to a file
- 2025, question 8 – Running a new program
- 2025, question 14 – Windows and Linux process creation
- 2025, question 20 – wait()
- 2025, question 22 – A simple shell: fill in the blanks
Practise this topic in the quiz (15 questions)