linux vfork函数有关问题
linux vfork函数问题
#include<stdio.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int cnt = 0;
vfork();
cnt++;
printf("%d\n", cnt);
return 0;
}
为什么输出有很多对1和2?
输出应该只有一对1和2才对啊!
------解决方案--------------------
子进程需要调用exit或者exec,这是vfork和fork的区别之一。
在return前面加一行_exit(0);
------解决方案--------------------
The vfork() function has the same effect as fork(), except that the behaviour 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(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.
#include<stdio.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int cnt = 0;
vfork();
cnt++;
printf("%d\n", cnt);
return 0;
}
为什么输出有很多对1和2?
输出应该只有一对1和2才对啊!
------解决方案--------------------
子进程需要调用exit或者exec,这是vfork和fork的区别之一。
在return前面加一行_exit(0);
------解决方案--------------------
The vfork() function has the same effect as fork(), except that the behaviour 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(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stddef.h>
int main(int argc, char *argv[])
{
int cnt = 0;
pid_t pid;
pid = vfork();
cnt++;
printf("%d\n", cnt);
if (pid == 0)
_exit(0);
return 0;
}