Pure
Pure

Reputation: 85

Closing all pipes of a process

I am working on making a program that will act in a similar way as a shell, but supports only foreground processes and pipes. I have multiple processes writing to the same pipe and some other properties that differ from the normal usage of pipes. Anyhow, my question is,

Is there any easy (automatic) way to close all file descriptors of a process except the three basic ones?

I am asking this question since I have a lot of difficulties keeping track of all file descriptors for every process. And sometimes they act in some unpredictable ways to me. It could be also because of the fact that I don't have a very thorough understanding of them.

Upvotes: 0

Views: 1457

Answers (2)

ntninja
ntninja

Reputation: 1325

Use the closefrom(3) C library function.

From the manpage:

The closefrom() system call deletes all open file descriptors greater than or equal to lowfd from the per-process object reference table. Any errors encountered while closing file descriptors are ignored.

Example usage:

#include <unistd.h>

int main() {
    // Close everything except stdin, stdout and stderr
    closefrom(3); // Were 3 is the lowest file descriptor you wish to close

    printf("Clear of all, but the three basic file descriptors!\n");
    return 0;
}

This works in most unices, but requires the libbsd support library for Linux.

Upvotes: 1

Celada
Celada

Reputation: 22261

Is there any easy way(automatic) to close all file descriptors of a process except the three basic ones?

The normal way to do this is to simply iterate over all of them and close them:

for (i = getdtablesize(); i > 3;) close(--i);

That's already a one-liner. It doesn't get any more "automatic" than that.

I am asking this question since I have a lot of difficulty keeping track of all file descriptors for every process.

It will be worth your time to think about the life cycle of each file descriptor you open, when it gets duplicated (e.g. dup2() and fork()), how it gets used, and make sure you account for how each one is going to get closed when it is no longer needed. Papering over a problem of leaked file descriptors by indiscriminately closing them all is not going to be sustainable.

I have multiple processes writing to the same pipe

If you do this, then you need to be aware that the order in which data arrive at the other end of the pipe is going to be unpredictable. It will be difficult to avoid corrupting the data stream.

Upvotes: 3

Related Questions