Implementing Multiprocessing in C: fork and exec

Implementing Multiprocessing in C: fork and exec

In operating systems, multiprocessing is an important mechanism that allows multiple processes to run simultaneously, thereby improving the efficiency and responsiveness of programs. In C language, <span>fork()</span> and <span>exec()</span> system calls are commonly used to create and manage new processes. This article will detail their working mechanisms and provide code examples to help beginners understand and apply these two functions.

1. <span>fork()</span> Function

1.1 Overview

<span>fork()</span> is a crucial system call used to create new processes. When a process successfully calls <span>fork()</span>, it clones itself and produces a child process. At this point, the parent and child processes will be two independent execution paths.

1.2 Return Values

  • Parent Process: Returns the PID (Process ID) of the child process
  • Child Process: Returns 0
  • Error: Returns -1

If the <span>fork()</span> call fails, for example due to resource limitations, it returns -1 and sets errno to indicate the reason.

1.3 Example Usage

Below is a simple example of using <span>fork()</span> to create a new child process:

#include <stdio.h>
#include <unistd.h> // Include unistd.h to use fork()
int main() {
    pid_t pid = fork(); // Create new child process
    if (pid < 0) { // If fork() fails
        perror("Fork failed");
        return 1;
    }
    if (pid == 0) { // Child process execution
        printf("I am the child process with PID: %d\n", getpid());
    } else { // Parent process execution
        printf("I am the parent process with PID: %d and my child's PID is: %d\n", getpid(), pid);
    }
    return 0;
}

Output Analysis

In the above code, when we run the program, we will see output similar to the following:

I am the parent process with PID: xxx and my child's PID is: yyy
I am the child process with PID: zzz

This indicates that both the parent and child processes are independently printing in their own context, where the PID corresponds to their unique identifiers.

2. <span>exec()</span> Family of Functions

2.1 Overview

<span>exec()</span> is a set of related functions used to load and execute a new executable file in the currently running program. Once <span>exec()</span> is successfully called, the original program content is replaced by the new program content.

2.2 Important Notes

After a successful call, <span>exec()</span> does not return to the original code segment. If an error occurs, it returns -1, and errno is set to indicate the error reason, such as file not found.

2.3 Example Usage

The following demonstrates how to use <span>execvp</span> to replace the program in the current process, executed by the previously created child process:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
    pid_t pid = fork(); // Create new child process
    if (pid < 0) {
        perror("Fork failed");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        printf("Child process executing ls command...\n");
        char *args[] = {"ls", "-l", NULL}; // Change command and its arguments
        execvp(args[0], args); // Execute new command
        perror("Exec failed"); // If execvp returns, an error occurred
        exit(EXIT_FAILURE);
    } else {
        wait(NULL); // Parent waits for child to finish
        printf("Parent process finished.\n");
    }
    return EXIT_SUCCESS;
}

Program Analysis and Result Demonstration

When the above code runs, you will first see the output “Child process executing ls command…”, followed by the display of all files in the specified directory. Even though the final printed message may still be from the parent process, the “ls” command enters the space in a different way, and the original position of the parent remains unaffected, allowing it to safely wait for the child task to complete.

Conclusion

This article briefly introduces the fundamental and important methods for implementing multiprocessing in C language—using the <span>fork</span> and <span>exec</span> methods. These tools not only help developers effectively utilize computer resources but also provide convenience for automating daily tasks. I hope this article helps you understand and apply multiprocessing techniques in C.

Leave a Comment