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;
}

输出结果为:
图片说明

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问