_此心安处是吾乡 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 用visual studi code完成html页面
    • ¥15 聚类分析或者python进行数据分析
    • ¥15 逻辑谓词和消解原理的运用
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
    • ¥20 腾讯企业邮箱邮件可以恢复么
    • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?