【问题标题】:Using a pipe to send integers from n child to the parent (c/unix)使用管道将整数从 n 个子级发送到父级(c/unix)
【发布时间】: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);
}

【问题讨论】:

    标签: c unix fork pipe


    【解决方案1】:

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

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

    【讨论】:

    • 是的,我没想到!这完全解决了问题!我只需要在循环中关闭管道并在循环中读取十次。如果我没记错的话,这也应该解决分叉“问题,因为父级现在在实际停止阅读之前循环叉子,是吗对吗?
    • 应该的。旁白:永远不要使用 scanf("%s");使用 scanf("%30s")。
    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 2021-06-19
    • 2023-03-03
    • 2015-05-10
    • 1970-01-01
    • 2018-05-17
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多