In Unix-like systems, fork() and exec() are two critical system calls for process management. They are commonly used to create new processes and execute new programs, but they serve distinct purposes.
1. fork()
The fork() system call creates a new process, known as the child process, which is a copy of the current process. The child process inherits most of the parent's environment, including code segments, heap, stack, and file descriptors. However, it has its own independent process identifier (PID). In the parent process, fork() returns the PID of the newly created child process, while in the child process it returns 0. If an error occurs, such as insufficient memory, fork() returns a negative value.
Example:
c#include <stdio.h> #include <unistd.h> int main() { pid_t pid = fork(); if (pid == 0) { // Child process code block printf("Hello from Child! "); } else if (pid > 0) { // Parent process code block printf("Hello from Parent! "); } else { // Error handling perror("fork failed"); } return 0; }
2. exec()
The exec() family of functions executes a new program within the context of the current process. This means the current process's code and data are replaced by the new program, but the process ID remains unchanged. This is typically used after fork(), where the child process loads and runs a completely new program using exec().
The exec() family includes multiple variants such as execl(), execp(), execle(), and execv(), which differ primarily in how parameters and environment variables are passed.
Example:
c#include <stdio.h> #include <unistd.h> int main() { pid_t pid = fork(); if (pid == 0) { // Child process executes exec execlp("ls", "ls", "-l", (char *)NULL); } else if (pid > 0) { // Parent process continues wait(NULL); // Waits for child process to finish } return 0; }
Summary
- Purpose:
fork()creates a child process identical to the current process;exec()executes a new program within the current process context. - Mechanism:
fork()creates a full copy with a different PID;exec()replaces the process content while keeping the PID unchanged. - Usage:
fork()andexec()are often used together: firstfork()creates a child process, then the child callsexec()to replace itself with another program. This pattern enables executing new programs without terminating the original process.
In practical applications, the combination of fork() and exec() is widely used, for example, in implementing shell programs where this mechanism is extensively employed to create and run user-specified commands.