孩子从std输入读取并写入std输出

时间:2013-11-18 04:23:51

标签: c fork pipe parent-child

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

#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);

}

1 个答案:

答案 0 :(得分:1)

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

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

与stdout类似。