首页 > 解决方案 > 创建多个命名管道

问题描述

我正在尝试制作一个程序,该程序可以生成由用户定义的多个孩子。父母必须使用命名管道(这是一项要求)与他的孩子来回发送信息。所以,我需要创建一些命名管道,这些命名管道的数量等于我要分叉的孩子的数量。我怎样才能有效地做到这一点,让每个孩子都知道他的烟斗叫什么名字?

pid_t childpid;
for(i = 0; i < numWorker; i++){
    // char *pipeName = "somename";
    // change the pipeName to reflect the child by adding a suffix
    // mkfifo(pipeName, 0666);
    childpid = fork();
    if(childpid < 0){
        perror("fork\n");
    }
    else if(childpid == 0){
        signal(SIGCONT, handleSignalChild);
        // how can I open the fifo here and then carry on reading and writing 
        //inside the while() below?
        break; // child exits the creation loop.
    }
}


// Main program execution begins here
while(1){

    if(childpid == 0){
        // read and write to the already opened pipes.
        //code to handle child execution.
    }
    else{
        // open all fifo pipes and get ready to read and write stuff.
        //code to handle parent execution.
    }

}

编辑:改写问题以使其更有意义。

标签: cforkmkfifo

解决方案


推荐阅读