使用管道将整数从n个子项发送到父项(c/unix)
我必须制作一个程序,读取一个数字,然后生成10个子进程。每个子级都必须在实际编号中查看其索引的出现次数(创建索引的for中使用的索引的距离),并将其发送回父级,以便他可以看到哪个索引的出现次数较大。我将举一个例子来说明: 假设我输入了号码012234555。使用管道将整数从n个子项发送到父项(c/unix),c,unix,fork,pipe,C,Unix,Fork,Pipe,我必须制作一个程序,读取一个数字,然后生成10个子进程。每个子级都必须在实际编号中查看其索引的出现次数(创建索引的for中使用的索引的距离),并将其发送回父级,以便他可以看到哪个索引的出现次数较大。我将举一个例子来说明: 假设我输入了号码012234555。 第一个子项(0)出现1次。 第二个(1)具有1。 第三个(2)有2个。 等等。 因此家长不得不说5是发生率最高的数字 我用管道把发生的事情从孩子传给父母,但实际上它只对第一个孩子有效。我做错了什么? 代码如下: #include <s
第一个子项(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);
}
#包括
#包括
#包括
#定义n10
内部主(空)
{
int i=0,max=0,j=0,tube[2],nbyte,w,occ,occv[10]={0},count=0;
pid_t pid,my_pid,child_pid;
字符缓冲区[30],检查;
printf(“插入编号:”);
scanf(“%s”,缓冲区);
my_pid=getpid();
如果(管道)
{
printf(“\n创建管道时出错!”);
退出(退出失败);
}
对于(i=0;i0);
printf(“我是父项(pid%d),最大出现次数为%d\n”,getpid(),max);
出口(0);
}
在第一次通过循环时,关闭父循环中的管[0]。因此,在通过循环的后续过程中,它不可供子级使用。实际上没有必要在这一点上关闭它
你也没有特别利用叉子——在第一个孩子终止之前,你不会叉子你的第二个孩子——但我不确定这个练习的目的是什么,所以这可能不是一个问题。是的,我没有想到这一点!这完全解决了问题!我只需要在循环中同时关闭管道和读取十次。如果我没有弄错的话,这也应该解决分叉问题,因为父级现在在实际停止读取之前循环分叉,是吗?应该。侧重点:永远不要使用scanf(“%s”);使用scanf(“%30s”)。