1.几个创建进程函数的对比
#fork():
源码:
#include
#include
#include
#include
int main()
{
pid_t pid;
if((pid=fork())<0)
{
printf ("fork error!\n");
exit(1);
}
else if(pid == 0)
{
printf ("in the child process!\n");
}
else
{
printf ("in the parent process!\n");
}
exit(0);
}
执行结果:
in the parent process!
in the child process!
分析:fork()调用一次,返回两次,分别在父进程和子进程返回(但是顺序不确定)
#vfork()
源代码:
#include
#include
#include
int gvar=2;
int main(void)
{
pid_t pid;
int var=5;
printf ("process id:%ld\n",(long)getpid());
printf ("gvar=%d var=%d", gvar,var);
if((pid=vfork())<0)
{
perror ("error!\n");
return 1;
}
else if(pid==0)
{
gvar--;
var++;
printf("the child process id:%ld\ngvar=%d var=%d\n"
,(long)getpid(),gvar,var);
_exit(0);
}
else
{
printf ("the parent process id:%ld\ngvar=%d var=%d\n"
,(long)getpid(),gvar,var);
return 0;
}
}
执行结果:
process id:12845
gvar=2 var=5the child process id:12846
gvar=1 var=6
the parent process id:12845
gvar=1 var=6
分析:若是把vfork()换成fork(),输入结果变为:
process id:12856
gvar=2 var=5the parent process id:12856
gvar=2 var=5
gvar=2 var=5the child process id:12857
gvar=1 var=6
说明,fork()创建进程时会复制父进程的资源,而vfork()不会复制父进程资源,与父进程共享地址空间