本文介绍了如何实现多进程的管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建多个进程和的我需要为每个进程创建两个命名管道。

有关每一个孩子,一个管道将用于从母公司int值;一个用于发送到int数组父。家长会做一些事情的,而从孩子的获得新的数据。

For each child, one pipe will be used to get int value from parent; one for sending to int arrays to parent. Parent will do some things while getting new data from childs.

该基地code:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // for reaching unix operations


int main(int argc, char *argv[]){
    pid_t main = getpid();

    int N = 30;
    int i;
    pid_t* children = (pid_t*) malloc(sizeof(pid_t) * N);
    for(i = 0; i < N; i++){
        pid_t child = fork();
        if ( child == 0){
            pid_t me = getpid();
            printf("I'm a child and my pid is: %d\n", me);
             sleep(1);
            // exit(4);
            return me * 2;
        } else if ( child < 0){
            // printf("Could not create child\n");
        } else {
            children[i] = child;
            // printf("I have created a child and its pid %d\n", child);
        }
    }

    // The child never reaches here
    for(i = 0; i < N; i++){
        int status;
        waitpid(children[i], &status, 0);
        printf("Process %d exited with return code %d\n", children[i], WEXITSTATUS(status));
    }
    return 0;
}

我试过很多事情没有成功,我迷路了。你能帮助我继续吗?

I tried many things with no success and I'm lost. Can you help me to continue?

任何帮助AP preciated!谢谢你。

Any help is appreciated! Thank you.

推荐答案

下面是如何建立一个管道每个子流程,使每个孩子写父:

Here's how to set up one pipe for each child process so that each child writes to the parent:

因为你需要为每一个孩子两个文件描述符,声明:

Since you need two file descriptors for each child, declare:

int fd[2 * N];

适当地初始化它们:

Initialize them appropriately:

for (int i = 0; i < N; i++) {
    pipe(&fd[2*i]);
}


I -th子进程,使用方法:


Inside the i-th child process, use:

write(fd[2*i + 1], write_buffer, SIZE)

写信给家长,并在家长使用:

to write to the parent, and in the parent use:

 read(fd[2*i], read_buffer, SIZE)

读我 -th孩子​​。

要关闭该管道:

I -th孩子​​,你可以使用

Inside the i-th child, you can use

close(fd[2*i])

向右走,看到,因为你只是写。你写完电话后

right away, seeing as you're only writing. After you're done writing call

close(fd[2*i + 1])

以关闭管道的写端

to close the write end of the pipe.

的情况是在父并行:从读书时,我 -th孩子​​可以

The situation is parallel in the parent: when reading from the i-th child you can

close(fd[2*i + 1])

向右走,因为你不写,你就大功告成了读调用后

right away, since you're not writing, and after you're done reading call

close(fd[2*i])

,关闭管的读端

由于需要的两个的每个子进程的管道,建立两个数组 - 为孩子们写于母公司包含一个管道,并包含一个管道父写给孩子

Since you need two pipes per child process, create two arrays - one containing pipes for the children writing to the parent, and one containing pipes for the parent writing to the children.

这篇关于如何实现多进程的管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 21:39