/* file name: vforktest.c
* cmd: $gcc vforktest.c
* author: yilonglucky#gmail.com
* description: demo the difference between vfork and fork
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int menu(void)
{
printf("# 1:fork 2:vfork others:quit >");
return 0;
}
int main()
{
int data = 0;
pid_t pid;
int choose=0;
menu();
while((choose = getchar()) == '1' || choose == '2')
{
getchar();
switch(choose)
{
case '1':
printf("parent:\tdata=%d fork()...\n",data);
pid=fork();
break;
case '2':
printf("parent:\tdata=%d vfork()...\n",data);
pid=vfork();
break;
case 'q':
return 0;
default:
printf("wrong input!\n");
goto again;
}
if(pid < 0)
{
perror("fork error\n");
}else if(pid == 0)
{
printf("child:\tdata=%d, data++, ",data);
data++;
printf("data=%d\n",data);
exit(0);
}
wait(pid);
printf("parent:\tdata=%d\n",data);
again:
menu();
}
return 0;
}
展示vfork与fork区别的样例
最新推荐文章于 2024-06-16 11:55:03 发布