[omniORB] RE: Fork/Exec

Alex Hayward xelah@xelah.com
Tue, 27 Feb 2001 11:10:07 +0000 (GMT)


On Tue, 27 Feb 2001, Sandro Tolaini wrote:
> It seems that the only way to fork/exec successfully (at least with Linux
> and FreeBSD) is to manually close all the open files (except for fd 0 (cin),
> 1 (cout) and 2 (cerr)) after fork() but before execv(). Something like:
> 
> ---------------------------------------
> pid_t pid = fork()
> 
> if ( pid == 0 )
> {
>     setsid();
>     int maxfd = getdtablesize();
>     for ( int fd = 3; fd < fdmax; fd++ )
>     {
>         close( fd );
>     }
> }
> 
> execv( exe, args );
> ---------------------------------------
> 
> Under Linux you can close only the file descriptors that are currently open
> by looking at /proc/self/fd directory, under which you'll find the opened
> files.

In case it matters you can also do this in a just as system specific but
much nicer way under FreeBSD with rfork(RFCFDG | RFPROC). This should
start the new process with a clean file descriptor table. Well, that's
what the man page says, I haven't actually /tried/ it...

I think rfork exists under NetBSD and OpenBSD, too.