Creating a Child Process [using vfork() function] - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Creating a Child Process [using vfork() function]

Share This

vfork() is a system call in Unix-like operating systems that is used to create a new process without copying the address space of the parent process. Unlike fork(), which creates a separate copy of the parent process's memory space, vfork() is more efficient as it avoids the overhead of copying the entire address space.

The vfork() function does not take any arguments. It returns the process ID (pid_t) of the child process in the parent process, and 0 in the child process. If an error occurs, it returns -1.

Important Note: The child process created by vfork() shares the memory space of the parent process. This means any changes made in the child process to variables or data also affect the parent process. Therefore, it is crucial to use exec or _exit immediately after vfork() in the child process to avoid issues.

Here is an example of how you might use vfork() to create a child process:

#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { pid_t pid; printf("Parent process: My PID is %d\n", getpid()); pid = vfork(); // Create a child process using vfork() if (pid == -1) { perror("vfork"); // Handle error if vfork fails return 1; } if (pid == 0) { // This code is executed by the child process printf("Child process: My PID is %d\n", getpid()); // Exec a new program in the child process execl("/bin/ls", "ls", "-l", (char *)NULL); // If exec fails, exit immediately _exit(1); } else { // This code is executed by the parent process printf("Parent process: Waiting for child to complete...\n"); wait(NULL); // Wait for the child process to complete printf("Parent process: Child process completed.\n"); } return 0; }
In this example, the parent process prints its PID, then creates a child process using vfork(). In the child process, it prints its PID and executes the ls -l command using execl(). The parent process waits for the child to complete using the wait() system call. After the child process completes, the parent process prints a message indicating that the child has finished.



Happy Exploring!

No comments:

Post a Comment