我有折叠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,我无法找出原因。有人能帮忙吗?
提前谢谢。
发布于 2018-04-01 06:30:55
错误实际上是来自子,而不是父。子程序使用系统调用运行test3之后,它会掉进default:情况,试图将它已经关闭的文件描述符fdopen。在系统调用之后添加break;,错误就会消失。
第二个问题是父文件中的close(fd[1]),它在刷新用fwrite编写的数据之前从文件指针下关闭文件描述符。要么将一个fflush(stream);调用放在close之前,要么去掉close,因为fclose将关闭文件描述符。
https://stackoverflow.com/questions/49595384
复制相似问题