C 使用fdopen时文件描述符不正确?

C 使用fdopen时文件描述符不正确?,c,pipe,file-descriptor,fdopen,C,Pipe,File Descriptor,Fdopen,我有下面的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

我有下面的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;
}  
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
int-fd[2];
char buf[]=“你好,世界!”;
if(管道(fd)){
佩罗(“管道”);
返回-1;
}
开关(fork()){
案例1:
佩罗尔(“福克”);
返回-1;
案例0:
//孩子
关闭(fd[1]);
dup2(fd[0],标准文件号);
关闭(fd[0]);
系统(“./test3”);
违约:
//母公司
关闭(fd[0]);
文件*stream=fdopen(fd[1],“w”);
if(stream==NULL){//错误检查
printf(“创建文件时出错”);
printf(“%s\n”,strerror(errno));
返回-1;
}
//将数据写入管道
fwrite(buf,1,6,流);
关闭(fd[1]);
fclose(流);
}
printf(“END~\n”);
返回0;
}  
下面是test3代码:

#include <stdio.h>
int main(){
     char n[1000];
     scanf("%s",n);
     printf("%s\n",n);
}
#包括
int main(){
charn[1000];
scanf(“%s”,n);
printf(“%s\n”,n);
}
我的问题是父级代码中的
fdopen
返回NULL,并出现
错误文件描述符错误
,我无法找出原因。有人能帮忙吗


提前感谢。

错误实际上来自孩子,而不是家长。在子系统使用系统调用运行
test3
之后,它将进入
默认值:
情况,尝试
fdopen
它已经关闭的文件描述符。添加
break在系统调用之后,错误将消失


第二个问题是父级中的
close(fd[1])
,它在刷新您用
fwrite
编写的数据之前,将文件描述符从文件指针下关闭。要么放入
fflush(流)
关闭
之前调用,或者干脆去掉
关闭
,因为
fclose
将关闭文件描述符。

我已经用了一上午的时间来处理这个问题。非常感谢!:)还有一个问题。假设我有一个将输入发送到test3的函数,我可以并且应该在每次调用该函数时打开一个流并关闭它吗?