C 如何获取文件描述符引用的文件指针?
我正在尝试使用dup2在以下代码中的父级和子级之间进行通信C 如何获取文件描述符引用的文件指针?,c,file-descriptor,file-pointer,C,File Descriptor,File Pointer,我正在尝试使用dup2在以下代码中的父级和子级之间进行通信 #include <stdio.h> #include <unistd.h> void main(int argv, char *argc) { int testpipe[2]; pipe(testpipe); int PID = fork(); if (PID == 0) { dup2(testpipe[0], 0); close
#include <stdio.h>
#include <unistd.h>
void main(int argv, char *argc) {
int testpipe[2];
pipe(testpipe);
int PID = fork();
if (PID == 0) {
dup2(testpipe[0], 0);
close(testpipe[1]);
execl("./multby", "multby", "3", NULL);
close(testpipe[0]);
close(0);
} else {
dup2(testpipe[1], 1);
close(testpipe[0]);
printf("5");
fclose(stdout);
close(testpipe[1]);
wait(NULL);
}
}
#包括
#包括
void main(int argv,char*argc){
int testpipe[2];
管道(测试管);
int-PID=fork();
如果(PID==0){
dup2(testpipe[0],0);
关闭(测试管[1]);
execl(“./multby”,“multby”,“3”,空);
关闭(测试管[0]);
关闭(0);
}否则{
dup2(测试管[1],1);
关闭(测试管[0]);
printf(“5”);
fclose(stdout);
关闭(测试管[1]);
等待(空);
}
}
我知道将输出写入stdout需要fclose。但是,如果我不使用stdout或stdin(也就是说,我不使用文件描述符1和0),我是否可以通过文件描述符获取引用的文件指针,以便获取文件指针作为fclose的参数?我想我不明白您的想法“如果我不使用stdout或stdin“。除了
stdout、stdin、stderr
之外,存在任何文件*
流的唯一方法是,如果您使用fopen
、fdopen
等打开了一个流,那么您就可以记住它是什么。一般来说,没有从文件描述符到流的映射,原因很简单,给定的文件描述符可能根本没有任何与之关联的流。(它也可能不止一个。)我认为这一切都不像你想象的那样有效。实际的管道描述符没有缓冲,它只是标准的I/O库,并且该缓冲不会跨越进程边界:在子级中,标准输出流与父级中完成的任何库缓冲无关。此外,子进程中的execl()
将子进程替换为正在执行的程序,因此它后面的行仅在失败时运行-通常在exec*
之后运行-另请参见-在注释中也会询问此问题。