您的位置:首页 > 运维架构 > Linux

linux下C的fork函数应用实例

2012-01-02 17:59 246 查看
最近在复习考试,顺便把一些心得写下来吧。

题目:写出一段程序,创建4个子进程,每个子进程都打印“Hello”后立刻终止,父进程等待4个子进程都终止后,打印“Bye”,然后终止。

答:这里有两种结构的程序,各位看哪种顺眼就看哪种吧~

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{   char *msg = "Hello";
pid_t pid;
int count = 0;

for(count = 0;count<4;count++)
{   pid = fork();
if (0 != pid)   //父进程执行
wait(NULL);
else    //子进程执行
{   printf("Child %d: ", count);
puts("Hello");
exit(0);
}
}
printf("Father : ");
puts("Bye");
exit(0);
}
/*
fork1:
pid = fork();
if (0 != pid)   //父进程执行
{   wait(NULL);
if (count < 3)
{   count++;
goto fork1;
}
else
{   printf("Father : ");
puts("Bye");
}
}
else    //子进程执行
{   printf("Child %d: ", count);
puts("Hello");
}

exit(0);
}*/


本文出自 “标题不能为空” 博客,请务必保留此出处http://hector.blog.51cto.com/4229131/756378
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: