关于fork使用进程的问题,懂得请进来!

ot310 2003-09-04 02:59:29
一个程序可以多次调用fork。类似地,每个子进程都可以使用fork来繁殖自己的“孩子”。为了证明这一点,编写一个程序,创建两个子进程。每个子进程再创建一个它们自己的子进程。在每个fork之后,每个父进程应使用printf来显示其后代进程的的进程id。

假设A创建了B和C,B创建了D、E,C创建了F、G,这程序不好写,我不明白怎么D、E、F、G是怎么知道它的父进程是谁啊?请会的人给个C语言的描述吧。
...全文
130 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ot310 2003-09-04
  • 打赏
  • 举报
回复
Thanks a lot!
syuui 2003-09-04
  • 打赏
  • 举报
回复
fork()在父进程中返回子进程的PID。在子进程中返回0
DEFG也用不着知道父进程的PID呀
zxm954712 2003-09-04
  • 打赏
  • 举报
回复
void main()
{
int pid = fork();
if (pid < 0 ) {
printf("Child process doesn't be created!");
return(-1);
}
if (pid == 0) { // A father process
int pid1 = fork(); // fork another child process
...
... // same judge
if (pid1 > 0) { // B child process
int pid3 = fork(); // B child process fork Dgrandchild process
}
if (pid > 0) { // C child process
printf("C child process pid is %d\n", pid);
int pid2 = fork(); // C child process fork F grandchild process
if (pid2 > 0) { // F grandchild process
printf(" F grandchild process pid is %d\n", pid2);
}
if (pid == 0) {
int pid4 = fork()
if (pid4 > 0) { // G grandchild process
printf(" G grandchild process pid is %d\n", pid4);
}
}
}
}

}
}

when you call the fork function , if the return value is large than 0, it is father process and if the return value is equal to 0, it is the child process. The fathar and child process will execute the same statement.
prettynacl 2003-09-04
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>

char flag[]="ABCDEFG";

main()
{
int i, stat = 0;
int child_id = -1;

for (i = 0; i < 2; i ++) {
child_id = fork();
if (child_id != 0) {
printf("father A :child %d,%c,id = %d\n",
i, flag[i +1], child_id);
stat ++;
}else{
break;
}
}

if (child_id == 0) {
for (i = 0; i < 2; i ++) {
child_id = fork();
if (child_id != 0) {
printf("father %c :child %d,%c,id = %d\n",
flag[1 + stat], i, flag[i + stat * 2 + 3],child_id);
}else{
break;
}
}
}
wait( &stat);
}
晨星 2003-09-04
  • 打赏
  • 举报
回复
人家题目只是要求你让父进程打印子进程的ID,又没要求子进程打印父进程ID。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧