问题
I am trying to understand the following piece of code
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid ;
unsigned int i=0;
pid=vfork();
switch(pid)
{
case -1: // some sort of error
puts("fork error");
break;
case 0: // the child process
while(i<100)
{
printf("%d\n", i);
i++;
}
break;
default: //parent
while(i<1000)
{
printf("%d\n", i);
i++;
}
break;
}
// _exit(0);
}
And please don't tell me that vfork() is bad and these kind of things .I know it is , but what is happening exactly in this code that is causing this kind of error . Thanks in advance
回答1:
It's unclear what you are trying to do or understand, but here is a slightly edited quote from the manual:
The vfork() function has the same effect as fork(2), except that the behavior is undefined if the process created by vfork() either
- modifies any data other than a variable of type pid_t used to store the return value from vfork()
- returns from the function in which vfork() was called
- calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions
You are doing both 1: i++
and 3 printf("%d\n", i)
. Whatever you expect, it won't work.
As a side note, vfork
isn't bad. Just tricky, dangerous, almost useless and removed from SUSv4.
来源:https://stackoverflow.com/questions/7778497/vfork-atexit-assertion-failed