Im really new to forking, what is the pid doing in this code? Can someone please explain what comes out at line X and line Y ?
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define SIZE 5
int nums[SIZE] = {0,1,2,3,4};
int main()
{
int i;
pid_t pid;
pid = fork();
if (pid == 0) {
for (i = 0; i < SIZE; i++) {
nums[i] *= -i;
printf("CHILD: %d ",nums[i]); /* LINE X */
}
}
else if (pid > 0) {
wait(NULL);
for (i = 0; i < SIZE; i++)
printf("PARENT: %d ",nums[i]); /* LINE Y */
}
return 0;
}
fork() in C This fork system call is used to create a new process. This newly created process is known as child process. The current process which is creating another child process is called the parent process. A child process uses the same program counter, CPU register, same files that are used by the parent process.
fork() returns 0 in the child process and positive integer in the parent process. Here, two outputs are possible because the parent process and child process are running concurrently. So we don't know whether the OS will first give control to the parent process or the child process.
fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process. The child process and the parent process run in separate memory spaces.
Under the hood, each process's memory page has a bit flag that is the copy-on-write flag that indicates whether that page should be copied before being written to. fork(2) marks every writeable page in a process with that bit. Each page also maintains a reference count.
fork()
duplicates the process, so after calling fork there are actually 2 instances of your program running.
How do you know which process is the original (parent) one, and which is the new (child) one?
In the parent process, the PID of the child process (which will be a positive integer) is returned from fork()
. That's why the if (pid > 0) { /* PARENT */ }
code works. In the child process, fork()
just returns 0
.
Thus, because of the if (pid > 0)
check, the parent process and the child process will produce different output, which you can see here (as provided by @jxh in the comments).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With