2

我有以下 C 代码。子进程用于运行 test3,其代码如下。父级用于将数据传递给将被重定向到 test3 的 STDIN 的子级。

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

int main(int argc, char *argv[]) {
    int fd[2];
    char buf[] = "HELLO WORLD!";
    if(pipe(fd)){
      perror("pipe");
      return -1;
    }
    switch(fork()){
        case -1:
            perror("fork");
            return -1;
        case 0:
            // child
            close(fd[1]);
            dup2(fd[0], STDIN_FILENO);
            close(fd[0]);
            system("./test3");
        default:
            // parent
            close(fd[0]);
            FILE* stream = fdopen(fd[1],"w");
            if(stream == NULL){ // error checking
                printf("Error creating a file\n");
                printf("%s\n", strerror(errno));
                return -1;
            }
            // write data to pipe
            fwrite(buf, 1,6,stream);
            close(fd[1]);
            fclose(stream);
    }
    printf("END~\n");
    return 0;
}  

这是test3代码:

#include <stdio.h>
int main(){
     char n[1000];
     scanf("%s",n);
     printf("%s\n",n);
}

我的问题是fdopen在父代码中返回 NULLBad file descriptor error并且我无法找出原因。任何人都可以帮忙吗?

提前致谢。

4

1 回答 1

2

错误实际上来自孩子,而不是父母。在孩子test3使用系统调用运行后,它会陷入default:困境,尝试访问fdopen它已经关闭的文件描述符。在系统调用后添加break;,错误就会消失。

第二个问题是close(fd[1])在父级中,它在刷新您使用fwrite. 要么fflush(stream);在 the 之前调用,close要么只是去掉close,因为fclose将关闭文件描述符。

于 2018-04-01T06:30:55.440 回答