【发布时间】:2014-02-15 02:30:00
【问题描述】:
我必须编写一个程序来读取一个数字,然后生成 10 个子进程。每个孩子必须以实际数量查看他的索引(创建它们的 for 中使用的索引的距离)的出现次数并将其发送回父级,以便他可以看到哪个具有更大的数量发生。我会做一个例子来说明清楚:
假设我输入了数字 012234555。
第一个孩子 (0) 出现了 1 次。
第二个 (1) 有 1。
第三个 (2) 有 2 个。
等等。
所以父母不得不说5是出现次数最多的数字。
我正在使用管道将事件从孩子发送到父母,但它实际上只适用于第一个孩子。我做错了什么? 这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#define N 10
int main (void)
{
int i=0,max=0,j=0,tube[2],nbyte,w,occ,occv[10]={0},count=0;
pid_t pid,my_pid,child_pid;
char buffer[30],check;
printf("Insert the nunmber: ");
scanf("%s",buffer);
my_pid=getpid();
if (pipe(tube))
{
printf("\nError while creating the pipe!");
exit(EXIT_FAILURE);
}
for (i=0;i<N;i++){
if ((pid=fork())<0)
{
printf("\nError while forking!");
exit(EXIT_FAILURE);
}
else if (pid==0) //child
{
occ=0;
close(tube[0]);
check = (char)(((int)'0')+i);
for (j=0;j<strlen(buffer);j++)
if (check==buffer[j])
occ++;
printf("I'm the child %d (pid %d), my occurence is %d\n",i,getpid(),occ);
if (occ>0)
{
nbyte=write(tube[1],&occ,sizeof(int));
printf("I'm the child %d and i wrote %d bytes (the actual integer is %d)\n",getpid(),nbyte,occ);
}
exit(i);
}
else //parent
{
close(tube[1]);
nbyte=read(tube[0],&(occv[i]),sizeof(int));
printf("I'm the parent pid(%d) and i read %d bytes (the actual integer is %d)\n",getpid(),nbyte,occv[i]);
if (occv[i]>max)
max=i;
}
}
while(wait(&w)>0);
printf("I'm the parent (pid %d) and the number with max occurence is %d\n",getpid(),max);
exit(0);
}
【问题讨论】: