fork and vfork
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int global=5;
int main(void)
{
pid_t pid;
int var=1,i;
printf("The difference between fork and vfork:\n");
pid=vfork();
switch(pid)
{
case 0:
i=3;
while(i-->0)
{
printf("Child process is running\n");
global++;
var++;
}
printf("Child End:global=%d,var=%d\n",global,var);
break;
case -1:
perror("fork error:");
exit(1);
default:
i=5;
printf("%10d\n",var);
while(i-->0)
{
printf("Parent process is running\n");
global++;
var++;
}
printf("Parent End:global=%d,var=%d\n",global,var);
exit(0);
}
}
The program running result as follows:
The difference between fork and vfork:
Child process is running
Child process is running
Child process is running
Child End:global=8,var=4
4359003
Parent process is running
Parent process is running
Parent process is running
Parent process is running
Parent process is running
Parent End:global=13,var=4359008
My question is: The value of 'var' is 4359003, why not 4 ?
[解决办法]
看看vfork 和fork的区别。。。。
[解决办法]
vfork最早起源于2.9BSD,它与fork的不同就在于它并不将父进程的地址空间完全复制到子进程中,因为子进程会立即调用exec.vfork出来的子进程是在父进程的空间中运行的,它的存在就是为了exec调用,所以它不需要复制这些东西。如果这时子进程修改了某个变量,这将影响到父进程.
vfork与fork的另一区别是:vfork保证子进程先运行,在它调用exec或exit后父进程才可能调度运行。如果在调用这两个函数之前子进程依赖于父进程的进一步动作,则会导致死锁。 而fork的父子进程运行顺序是不定的,它取决于内核的调度算法.
http://blog.csdn.net/buaalei/article/details/5348382
[解决办法]
改下面的就可以。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int global=5;
int main(void)
{
pid_t pid;
int var=1,i;
printf("The difference between fork and vfork:\n");
pid=vfork();
switch(pid)
{
case 0:
i=3;
while(i-->0)
{
printf("Child process is running\n");
global++;
var++;
}
printf("Child End:global=%d,var=%d\n",global,var);
break;
case -1:
perror("fork error:");
exit(1);
default:break;
}
i=5;
printf("%10d\n",var);
while(i-->0)
{
printf("Parent process is running\n");
global++;
var++;
}
printf("Parent End:global=%d,var=%d\n",global,var);
exit(0);
}
The difference between fork and vfork:
Child process is running
Child process is running
Child process is running
Child End:global=8,var=4
4
Parent process is running
Parent process is running
Parent process is running
Parent process is running
Parent process is running
Parent End:global=13,var=9
[解决办法]
首先,运行在哪个环境?cygwin?linux? 对vfork实现有差异
其次,如果在linux下
vfork的MAN手册中说其是未定义的.
The vfork() function has the same effect
as fork(), except that the behaviour is undefined if the process cre-
ated 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.
因为在退出前调用了printf函数,去掉printf,lz再试试呢