【问题标题】:Child reading from std input and writes to std output子级从标准输入读取并写入标准输出
【发布时间】:2013-11-18 04:23:50
【问题描述】:

我有一个程序,其中子进程运行一个程序,但父进程将一个数字传递给子进程,然后子进程将响应写回父进程。但是,每当我运行代码时,它并没有给我任何回报,所以我一定是错误地传递或接收孩子,但我不确定如何。任何帮助表示赞赏。这是我的代码:

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


int main() {

int pid;
int n;
char buf[101];
int pfdA[2];
int pfdB[2];

// CREATES FIRST PIPE
if (pipe(pfdA) == -1) {
    perror("pipe failed");
    exit(-1);
}

// CREATES SECOND PIPE
if (pipe(pfdB) == -1) {
    perror("pipe failed");
    exit(-1);
}   

// FORK()
if ((pid == fork()) < 0) {
    perror("fork failed");
    exit(-2);
}


    if (pid == 0 ) {
    // duplicate file descriptor 0 to point to FIRST pipe
    dup(pfdA[0]);

    // CLOSES ends of FIRST pipe you don't need anymore
    close(pfdA[0]);
    close(pfdA[1]);

    // duplicates file descriptor 1 to point to SECOND pipe
    dup(pfdA[1]);


    // CLOSES ends of SECOND pipe you don't need anymore
    close(pfdB[0]);
    close(pfdB[1]);

            execlp("./A5_CHILD", "./A5_CHILD", (char *) 0);
            perror("execlp");
            exit(-3);
    } 

else {

    while( 1 ) {
            char NUM[100];
            close(pfdA[0]);
            close(pfdB[1]);

            int r=0;

            printf("Enter a Number: ");
            fflush(stdout);
            scanf("%s", NUM);

    // SENDS   NUM   to Child process
    write(pfdA[1], NUM, strlen(NUM));


    // READS FROM CHILD THE RESPONSE into the variable buf and
    //      store the return value from read() into the variable r
    r= read(pfdB[0], buf, 100);

    if( r > 0 ) {
                    buf[r] = '\0';
                    printf("%s\n", buf);
                    fflush(stdout);
            }
            else {
                    printf("[PARENT] Reading from child: read() returned %d\n", r);
                    break;
            }
    }
}

    return(0);

}

【问题讨论】:

  • 调试器可以帮助您缩小您做错的部分。
  • 你在哪里打开/创建文件描述符?
  • @nhgrif 这绝对是一个损坏的管道,所以调试器说,但我不知道从这里去哪里
  • 注意:恕我直言,您最好发送\0,就像write(pfdA[1], NUM, strlen(NUM)+1);一样

标签: c fork pipe parent-child


【解决方案1】:

除非您明确地close(0),否则dup(pfdA[0]) 几乎肯定不会返回0。尝试dup2 指定您想要哪个描述符作为新描述符。即(为简洁起见省略了错误检查):

dup2( pfdA[0], STDIN_FILENO );
close( pfdA[0])

标准输出也是如此。

【讨论】: