fork函数创建子进程后,父子进程是独立、同时运行得,而且没有先后顺序
vfork()产生的父子进程,一定是子进程先运行完,再运行父进程
直接上代码
fork()
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
int main(void)
{
pid_t child;
/* 创建子进程 */
if((child=fork())==-1)
{
printf("Fork Error : %s\n", strerror(errno));
exit(1);
}
else
if(child==0) // 子进程
{
printf("I am the child_pid: %d\n", getpid());
exit(0);
}
else //父进程
{
printf("I am the father_pid:%d\n",getpid());
return 0;
}
}
打印结果:
父子进程无顺序运行
vfork()
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
int main(void)
{
pid_t child;
/* 创建子进程 */
if((child=vfork())==-1)
{
printf("Fork Error : %s\n", strerror(errno));
exit(1);
}
else
if(child==0) // 子进程
{
sleep(2); //子进程睡眠2秒
printf("I am the child: %d\n", getpid());
exit(0);
}
else //父进程
{
printf("I am the father:%d\n",getpid());
exit(0);
}
}
结果:

图中 运行结果 8256的进程是2秒后出现,随后出现8255。
本文对比了fork和vfork函数在创建子进程后的运行特性。fork函数创建的父子进程独立运行,顺序不定;而vfork确保子进程先于父进程运行完毕。通过代码示例详细解析了两种函数的行为差异。
1360

被折叠的 条评论
为什么被折叠?



