繁体   English   中英

使用管道将整数从n个子对象发送到父对象(c / unix)

[英]Using a pipe to send integers from n child to the parent (c/unix)

我必须编写一个读取数字的程序,然后生成10个子进程。 每个孩子都必须查看实际编号中索引的出现情况(在为其创建索引时使用的索引的距离),然后将其发回给父级,以便他可以看到哪个索引的编号更大出现次数。 我将举例说明一下:假设我输入数字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);
}

在第一次通过循环时,关闭父级中的tube [0]。 因此,此子项在后续循环中对孩子不可用。 实际上,此时不必关闭它。

您也没有特别利用分叉的优势-在第一个孩子终止之前不要分叉第二个孩子-但我不确定该练习的目的是什么,所以这可能不是问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM