How close pipe handle in unix? (fclose() of pclose())?
If 开发者_JS百科I create pipe in unix this way:
int fds[] = {0, 0};
pipe(fds);
Then make FILE *
from fds[0]
this way:
FILE *pipe_read = fdopen(fds[0], "rt");
Then how should I close this file (pipe_read
)?
fclose(pipe_read)
pclose(pipe_read)
close(fileno(pipe_read))
fdopen
returns a FILE*
so you should fclose
it. This will also close the underlying file descriptor as well.
The pclose
call is meant for closing a handle created with popen
, a function you use for running a command and connecting to it with pipes.
The close
call will close the underlying file descriptor but, unfortunately, before the file handle has had a chance to flush its data out - in other words, you're likely to lose data.
You should use fclose(pipe_read).
close() closes the file descriptor in the kernel. It's not enough because the file pointer is not free. So you should use fclose() on pipe_read, which will also take care of closing the file descriptor.
精彩评论