UNIX操作系统中,fork()系统调用用于创建进程。仔细阅读、分析下列程序,假设程序正确运行并创建子进程成功,那么,输出到屏幕的正确结果是main()
{
pid_t pid;
pid = fork();
if (pid = = 0) printf ("Hello World\n");
else if (pid > 0) printf ("Hello World\n");
else printf ("Hello World\n");
}
我不太理解你为什么说用fork()创建线程。
我觉得,你不应该把父子进程输出都统一
这样,就像楼上所说的全是hello world
这样不便于分析。
看看如下代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#define err_exit(msg) (perror(msg),(exit(1)))
int main(void)
{
pid_t pid;
pid=fork();
if(pid==0){
puts("I am child ..");
}else if(pid>0){
puts("I am parent ..");
}else{
err_exit("fork()");
}
return 0;
}
```
结果如下:
I am parent ..
I am child ..
这样似乎还是没有分析出他们具有父子关系。
所以再修改代码:
#include
#include
#include
#include
#define err_exit(msg) (perror(msg),(exit(1)))
int main(void)
{
pid_t pid;
pid=fork();
if(pid==0){
puts("I am child ..");
printf("My father pid==%d\n",getppid());
sleep(30);
}else if(pid>0){
puts("I am parent ..");
printf("My child pid==%d\n",pid);
wait();
}else{
err_exit("fork()");
}
return 0;
}
得到结果如下:
I am parent ..
My child pid==3926
I am child ..
My father pid==3925
在程序睡眠期间。我们调用系统工具
pstree -p |grep t27
查到如下结果:
|-gnome-terminal(3503)-+-bash(3511)---t27(3925)---t27(3926)
这样你应该能比较清晰理解父子进程的关系。
希望能帮到你!
这里有全套的答案
http://www.docin.com/p-895099432.html
就是各种Hello World
取决于子进程创建是否成功,子进程跟父进程printf的先后顺序