Reputation: 746
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 pipefds[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
Upvotes: 7
Views: 4016
Reputation: 11
as Steve mentioned above, we might not know kernel's business but looking further at close syscall docs (close(2)) we can see:
If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description are freed;
https://linux.die.net/man/2/close
Upvotes: 1
Reputation: 279455
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 :-)
Upvotes: 8
Reputation: 169478
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.
Upvotes: 0
Reputation: 42159
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.
Upvotes: 5