_此心安处是吾乡 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 Arcgis相交分析无法绘制一个或多个图形
    • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
    • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
    • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
    • ¥30 3天&7天&&15天&销量如何统计同一行
    • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
    • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
    • ¥15 vs2019中数据导出问题
    • ¥20 云服务Linux系统TCP-MSS值修改?
    • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)