Unix 中的管道手柄有多近?(fclose() of pclose()).

How close pipe handle in unix? (fclose() of pclose())?

本文关键字:pclose fclose of 管道 Unix      更新时间:2023-10-16

如果我以这种方式在 unix 中创建管道:

int fds[] = {0, 0};
pipe(fds);

然后以这种方式从fds[0]进行FILE *

FILE *pipe_read = fdopen(fds[0], "rt");

那么我应该如何关闭这个文件(pipe_read(?

  1. fclose(pipe_read)
  2. pclose(pipe_read)
  3. close(fileno(pipe_read))

fdopen返回一个FILE*,所以你应该fclose它。这也将关闭基础文件描述符。

pclose调用用于关闭使用 popen 创建的句柄,该函数用于运行命令并使用管道连接到它。

close调用将关闭基础文件描述符,但不幸的是,在文件句柄有机会刷新其数据之前 - 换句话说,您可能会丢失数据。

你应该使用 fclose(pipe_read(。

close(( 关闭内核中的文件描述符。这还不够,因为文件指针不是免费的。所以你应该在pipe_read上使用 fclose((,这也将负责关闭文件描述符。