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

时间:2018-04-01 06:25:01

标签: 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 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返回带Bad file descriptor error的NULL,我无法弄清楚原因。任何人都可以帮忙吗?

提前致谢。

1 个答案:

答案 0 :(得分:2)

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

第二个问题是父级中的close(fd[1]),它在刷新您使用fwrite编写的数据之前从FILE指针下关闭文件描述符。要么在fflush(stream);之前拨打close,要么只删除close,因为fclose会关闭文件描述符。

相关问题