Welcome to our comprehensive guide on the fork() system call in C programming! This tutorial is designed for beginners and intermediate learners, so let's dive in together. 🤝
The fork() system call is a powerful tool in C programming that allows a process to create a duplicate (or child) process of itself. The parent process (the original process) and the child process both continue execution from the exact point where the fork() call was made.
The fork() system call is useful in various scenarios, such as:
fork().fork() call.fork() is different in the parent and child processes:
Here's a simple example of using fork() to create a child process that prints a message.
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid < 0) { // Error occurred
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid > 0) { // Parent process
printf("Parent: Continuing with parent process\n");
} else { // Child process
printf("Child: Continuing with child process\n");
}
return 0;
}In this example, we'll demonstrate how changes made to a shared variable are visible in both the parent and child processes.
#include <stdio.h>
#include <unistd.h>
int main() {
int shared_var = 42;
pid_t pid = fork();
if (pid < 0) { // Error occurred
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid > 0) { // Parent process
printf("Parent: Changing shared_var to 69\n");
shared_var = 69;
} else { // Child process
printf("Child: Starting with shared_var as %d\n", shared_var);
}
printf("Parent: shared_var is now %d\n", shared_var);
printf("Child: shared_var is now %d\n", shared_var);
return 0;
}What is the return value of `fork()` in the parent process?
Happy learning! 🚀