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

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


}

最佳答案

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

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


对于stdout同样。

10-08 04:13