How to close a pipe handle in unix? (fclose () pclose ())?

If I create a channel in unix as follows:

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

Then do FILE * from fds[0] as follows:

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

Then how to close this file ( pipe_read )?

  • fclose(pipe_read)
  • pclose(pipe_read)
  • close(fileno(pipe_read))
0
source share
2 answers

fdopen returns a FILE* , so you should fclose it. This will also close the underlying file descriptor.

The pclose call is intended to close the handle created with popen , the function you use to run the command and connect to it using pipes.

Calling close will close the underlying file descriptor, but unfortunately, before the file descriptor had the ability to flush its data, in other words, you are likely to lose data.

+4
source

You should use fclose (pipe_read).

close () closes the file descriptor in the kernel. This is not enough because the file pointer is not free. Therefore, you should use fclose () on pipe_read, which will also take care of closing the file descriptor.

+1
source

Source: https://habr.com/ru/post/952052/


All Articles