Does Linux automatically free an unnamed pipe once both file descriptors have been closed?
I am using an unnamed pipe for interprocess communication between a parent process and a child process created through fork(). I am using the pipe() function included in unistd.h
I would assume that once both file descriptors have been closed (and in both processes), that the pipe is deallocated/freed/destroyed/etc. But I haven't found anything in the man pages that says this definitively. I am making a program that will run for a very long time, so I want to prevent memory leaks and other things of that nature.
My function body looks something like:
int pipefd开发者_开发技巧s[2];
pipe( pipefds );
if ( fork() == 0 ) {
close( pipefds[1] );
...
//Use pipefds[0]
close( pipefds[0] );
} else {
close( pipefds[0] );
...
//Use pipefds[1]
close( pipefds[1] );
}
Is it safe to assume that after this function terminates in both the child and the parent that the pipe has been deallocated/freed/destroyed/etc. ?
Is there any documentation that says this definitively?
Thank you
http://www.opengroup.org/onlinepubs/009695399/functions/close.html
When all file descriptors associated with a pipe or FIFO special file are closed, any data remaining in the pipe or FIFO will be discarded.
Doesn't actually say that all resources are freed, since internal kernal gubbins isn't "data remaining in the pipe", but I think we can safely assume that if your kernel keeps anything after that, that's your kernel's business and none of yours :-)
The documentation of close
says this.
The close() call deletes a descriptor from the per-process object reference
table. If this is the last reference to the underlying object, the
object will be deactivated.
Well, about the only thing you can do is close both ends of the pipe, right? Yes, the pipe will be deallocated once all handles to both ends of the pipe are closed.
精彩评论