使用 fdopen 时文件描述符错误?

Bad file descriptor when using fdopen?

我有以下 C 代码。 child用于运行test3,其代码如下。 parent 用于将数据传递给 child ,后者将被重定向到 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);
}

我的问题是 parent 代码 returns 中的 fdopenBad file descriptor error 为 NULL,我无法找出原因。有人可以帮忙吗?

提前致谢。

错误实际上来自 child,而不是 parent。在 child 通过系统调用运行 test3 之后,它会陷入 default: 的情况,试图 fdopen 它已经关闭的文件描述符。在系统调用后添加 break; 错误将消失。

第二个问题是 parent 中的 close(fd[1]),它会在刷新您使用 fwrite 写入的数据之前从 FILE 指针下关闭文件描述符。要么在 close 之前调用 fflush(stream);,要么干脆去掉 close,因为 fclose 会关闭文件描述符。