通过C中的中心功能管理管道

时间:2016-10-23 16:47:01

标签: c linux pipe fork

我试图让一个带有fork的程序,我试图使用管道在父母和孩子之间进行通信,但我希望它们由一个中心函数管理(一个用于父级和一个用于孩子)和通过它们进行的通信,而不是将管道末端作为变量 如下面的代码所示,我有一个函数function_manager,另一个是message_to_father(char * s)。我希望function_manager中的所有函数都能够使用message_to_father而无需发送管道" out"结束为每个参数,然后使用该参数调用message_to_father。有没有办法让message_to_father知道如何使用没有参数的管道?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

//son

void message_to_father(char *s){
    // write(out, s, 19);
}

/*
//version that I don't want
void message_to_father(int out, char *s){
    // write(out, s, 19);
}
*/

void function_manager(int in, int out){
    //function_1(p1, p2, ...) //This would be better
    //function_2(out, p1, p2) // I don't want like this
    //function_3()
}

//parent

void message_to_son(char *s){
    // write(out, s, 19);
}

void user_interface_manager(int in, int out){

}

void initialize(){
    int pipe_father_to_son[2], pipe_son_to_father[2];
    pid_t pid;
    pipe (pipe_father_to_son);
    pipe (pipe_son_to_father);
    pid = fork();
    switch (pid) {
        case -1:
            perror("fork()");
            exit(1);
            break;
        case 0:
            close(pipe_father_to_son[1]);
            close(pipe_son_to_father[0]);

            function_manager(pipe_father_to_son[0], pipe_son_to_father[1]);

            close(pipe_father_to_son[0]);
            close(pipe_son_to_father[1]);
            break;
        default:
            close(pipe_father_to_son[0]);
            close(pipe_son_to_father[1]);

            user_interface_manager(pipe_son_to_father[0], pipe_father_to_son[1]);

            close(pipe_father_to_son[1]);
            close(pipe_son_to_father[0]);
            wait(NULL);

    }
}

int main (int argc, char *argv[])
{
    initialize();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您使用的是C语言,而不是C ++或Java。这意味着一个功能,一个任务。您不能拥有具有多个功能和多个任务的类。这也意味着你不能拥有隐含的论点。

所以,不,你想要的是不可能的。要使用的管道必须是显式参数,为了保持设计的正确性,必须使用多个函数。