_此心安处是吾乡 2018-09-26 11:29 采纳率: 0%
浏览 603

linux c pipe父进程与多子进程通信时读取为空字符串

环境是linux c语言,父进程与多个子进程之间通过无名管道pipe进行通信
首先创建多个子进程,并将子进程的输入输出重定位到stdin和stdout,然后进行两次write,代码如下

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

int main(){
    int hubToPlayer[26][2];
    int playerToHub[26][2];
    pid_t pid[26];
    for(int i = 0; i < 2; i++){
        if(pipe(hubToPlayer[i]) < 0){
            perror("Bad start\n");
            return 5;
        }
        if(pipe(playerToHub[i]) < 0){
            perror("Bad start\n");
            return 5;
        }

        pid[i] = fork();
        if(pid[i] < 0){
            perror("Bad start\n");
            return 5;
        }else if(pid[i] == 0){
            close(hubToPlayer[i][1]);
            dup2(hubToPlayer[i][0], 0);
            close(hubToPlayer[i][0]);
            close(playerToHub[i][0]);
            dup2(playerToHub[i][1], 1);
            close(playerToHub[i][1]);

            char playerID[2];
            sprintf(playerID, "%d", i);
            if(execlp("./a.out", "./a.out", "2", playerID, NULL) < 0){
                perror("Error raised by exec\n");
                exit(1);
            }
        }else{
            close(hubToPlayer[i][0]);
            close(playerToHub[i][1]);
        }

        for(int i = 0; i < 2; i++){
            char command[30];
            sprintf(command, "tokens%d", 7);
            write(hubToPlayer[i][1], command, strlen(command) + 1);
            write(hubToPlayer[i][1], "1", strlen("1") + 1);
        }
    }
    return 0;
}

子进程进行两次读入,代码如下

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[]){
    char playerNum = 'A' + atoi(argv[2]);
    char msg[BUFSIZ];
    scanf("%s", msg);
    fprintf(stderr, "The massage shenzi %c readed is %s\n", playerNum, msg);
    char msg1[BUFSIZ];
    scanf("%s", msg1);
    fprintf(stderr, "The massage shenzi %c readed is %s\n", playerNum, msg1);
    return 0;
}

输出结果为:
图片说明

每个子进程都是第一次输入的读取没问题,但是之后读取到的字符串全部为空字符串。有没有大神知道是为什么,非常感谢

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
    • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
    • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
    • ¥20 matlab yalmip kkt 双层优化问题
    • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
    • ¥88 实在没有想法,需要个思路
    • ¥15 MATLAB报错输入参数太多
    • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
    • ¥15 有赏,i卡绘世画不出