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
#
Simplest example for fork()
printf("I'm printed once!\n");
fork();
// Now there are two processes running one is parent and another child.
// and each process will print out the next line.
printf("You see this line twice!\n");
The return value of fork(). Return value -1= failed; 0= in child process; positive = in parent process (and the return value is the child process id)
pid_t id = fork();
if (id == -1) exit(1); // fork failed
if (id > 0)
{
// I'm the original parent and
// I just created a child process with id 'id'
// Use waitpid to wait for the child to finish
} else { // returned zero
// I must be the newly made child process
}
What is different in the child process than the parent process?
Now let's visualize your program code
pid_t pid;
pid = fork();
Now OS make two identical copies of address spaces, one for the parent and the other for the child.
Both parent and child process start their execution right after the system call fork(). Since both processes have identical but separate address spaces, those variables initialized before the fork() call have the same values in both address spaces. Every process has its own address space so any modifications will be independent of the others. If the parent changes the value of its variable, the modification will only affect the variable in the parent process's address space. Other address spaces created by fork() sysem calls will not be affected even though they have identical variable names .
Here parent pid is non-zero, it calls function ParentProcess(). On the other hand, the child has a zero pid and it calls ChildProcess() as shown below:
In your code parent process call wait()
it pauses at that point until the child exits. So the child's output appears first.
if (pid == 0) {
// The child runs this part because fork returns 0 to the child
for (i = 0; i < SIZE; i++) {
nums[i] *= -i;
printf("CHILD: %d ",nums[i]); /* LINE X */
}
}
OUTPUT from child process
what comes out at line X
CHILD: 0 CHILD: -1 CHILD: -4 CHILD: -9 CHILD: -16
Then after the child exits, the parent continues from after the wait() call and prints its output next.
else if (pid > 0) {
wait(NULL);
for (i = 0; i < SIZE; i++)
printf("PARENT: %d ",nums[i]); /* LINE Y */
}
OUTPUT from parent process:
what comes out at line Y
PARENT: 0 PARENT: 1 PARENT: 2 PARENT: 3 PARENT: 4
At last both output combined by child and parent process will be shown on terminal as follow:
CHILD: 0 CHILD: -1 CHILD: -4 CHILD: -9 CHILD: -16 PARENT: 0 PARENT: 1 PARENT: 2 PARENT: 3 PARENT: 4
For more info refer this link