#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
pid = vfork();
if(pid>0)
{
while(1)
{
printf("this is father print,pid= %d\n",getpid());
sleep(1);
}
}
else if(pid == 0)
{
while(1){
printf("this is child print,child pid =%d\n",getpid());
sleep(1);
}
}
return 0;
}
用vfork结果保证子进程先运行:
用vfork结果保证子进程先运行子进程调用exit()后子进程退出,父进程执行
#include <sys/types.h>
#include <unistd.h>
#include<stdlib.h>
#include <stdio.h>
int main()
{
pid_t pid;
int cnt=0;
pid = vfork();
if(pid>0)
{
while(1)
{
printf("cnt = %d\n",cnt);
printf("this is father print,pid= %d\n",getpid());
sleep(1);
}
}
else if(pid == 0)
{
while(1){
printf("this is child print,child pid =%d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3)
{
exit(0);
}
}
}
return 0;
}