You didn't specify what language you are developing in, but since you mentioned system()
, I assume you mean C or C++.
Typically this is accomplished by using fcntl() to set the close-on-exec flag on those file descriptors that you do not want to be inherited:
int fd = open("somefile", O_RDONLY);
fcntl(fd, F_SETFD, FD_CLOEXEC);
You could also do it the brute force way by iterating through all possible fd's in the child process after you fork but before you exec. This is a bit trickier because it requires that you know what the maximum possible fd value is, and it is also less efficient because you'll end up iterating through and "closing" a bunch of unused fd's. Something like this:
pid_t pid = fork();
switch (pid) {
case 0:
// In the child process. Iterate through all possible file descriptors
// and explicitly close them.
long maxfd = sysconf(OPEN_MAX);
for (long i = 0; i < maxfd; ++i) {
close(i);
}
// Now exec the new program, file-handle free.
execlp("someprogram", "arg1", "arg2");
break;
case -1:
// TODO: handle errors.
break;
default:
// Parent process.
int status;
pid_t finished = waitpid(pid, &status, 0);
break;
}
Hope that helps,
Eric Melski