The following code never ends. Why is that?
#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 = vfork();
if(pid == 0){ /* Child process */
for(i = 0; i < SIZE; i++){
nums[i] *= -i;
printf(”CHILD: %d “, nums[i]); /* LINE X */
}
}
else if (pid > 0){ /* Parent process */
wait(NULL);
for(i = 0; i < SIZE; i++)
printf(”PARENT: %d “, nums[i]); /* LINE Y */
}
return 0;
}
Update:
This code is just to illustrate some of the confusions I have regarding to vfork()
. It seems like when I use vfork()
, the child process doesn't copy the address space of the parent. Instead, it shares the address space. In that case, I would expect the nums array get updated by both of the processes, my question is in what order? How the OS synchronizes between the two?
As for why the code never ends, it is probably because I don't have any _exit()
or exec()
statement explicitly for exit. Am I right?
UPDATE2:
I just read: 56. Difference between the fork() and vfork() system call?
and I think this article helps me with my first confusion.
The child process from vfork() system call executes in the parent’s address space (this can overwrite the parent’s data and stack ) which suspends the parent process until the child process exits.
int main( void )
The 80's were a long time ago. – William Pursellvfork
: "It is rather unfortunate that Linux revived this spectre from the past". Given thatfork
is (in any version of Linux you're likely to be using) a lightweight operation, I'd stop worrying about whatvfork
might or might not do. – Philip Kendallvfork
semantics of suspending the parent but still do a copy of the address space like normalfork
. The reason for that is that there were many bugs caused by sharing the address space (I seem to remember execvp on some system calling malloc and leaking memory in the parent). – Art"Instead, it shares the address space."
is not correct.. I like to read more :) In my knowledgevfork()
, creates new process that shares the same address as calling process – Grijesh Chauhansys_vfork
. If it was sharing the address space the call tofork1
would have the flagFORK_SHAREVM
, it doesn't. I know that other operating systems made the same choice, can't recall which ones at this moment. Last time I researched this was 10 years ago. – Art