Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Linux automatically free an unnamed pipe once both file descriptors have been closed?

Tags:

c

linux

pipe

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

like image 206
pcd6623 Avatar asked Dec 08 '10 21:12

pcd6623


2 Answers

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 :-)

like image 94
Steve Jessop Avatar answered Sep 23 '22 05:09

Steve Jessop


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.
like image 42
Arkku Avatar answered Sep 21 '22 05:09

Arkku