我的任务是编写一个在循环中创建10个子进程的C程序,每个进程都会通过公共管道将其ID发送给父进程,父进程将分别打印每个子进程的ID,然后打印所有子进程的总和儿童身份证。
我的尝试如下:
#include <stdio.h>
#include <sys/types.h>
#include <windows.h>
#include <unistd.h>
int main(void){
int sum=0;
int id=0;
int descriptors[2];
int children[10];
pipe(descriptors);
printf("Dad's pid : %d \n",getpid());
for(int i=0;i<10;i++){
int x=fork();
if(x== (pid_t) 0){
close(descriptors[0]);
id=getpid();
children[i]=getpid();
printf("Process id %d \n",getpid());
write(descriptors[1],&id,sizeof(id));
exit( 0 );
}
else if(x> (pid_t) 0){
close(descriptors[1]);
read(descriptors[0],&id,sizeof(id));
children[i]=id;
sum=sum+id;
}
}
for(int i=0;i<10;i++){
printf("child process %d's ID : %d from parent : %d \n",i,children[i],getpid());
}
printf("The total sum of children IDs is : %d \n", sum);
return 0;
}
经过几次尝试后,我决定添加printf进程id行以试图查看故障发生的位置,这是结果输出:
Dad's pid : 18240
Process id 24100
Process id 4900
Process id 21924
Process id 23168
Process id 4820
Process id 10568
Process id 22152
Process id 6100
Process id 21868
child process 0's ID : 24100 from parent : 18240
child process 1's ID : 24100 from parent : 18240
child process 2's ID : 24100 from parent : 18240
child process 3's ID : 24100 from parent : 18240
child process 4's ID : 24100 from parent : 18240
child process 5's ID : 24100 from parent : 18240
child process 6's ID : 24100 from parent : 18240
child process 7's ID : 24100 from parent : 18240
child process 8's ID : 24100 from parent : 18240
child process 9's ID : 24100 from parent : 18240
The total sum of children IDs is : 241000
Process id 22824
这显然不是理想的结果。为什么第一个子进程的id会因所有进程ID而重复?为什么最后有一个额外的父进程在最后打印总和之后给出了进程id行? 提前谢谢!