Subject: Re: fork/vfork and file descriptors problems
To: Kim Ludwig <ludwig@grc.nasa.gov>
From: Michael Richardson <mcr@sandelman.ottawa.on.ca>
List: netbsd-help
Date: 02/16/2000 00:05:07
>>>>> "Kim" == Kim Ludwig <ludwig@grc.nasa.gov> writes:
    Kim> First of all, I am using NetBSD 1.3.3 and gcc 2.7.2.2+myc2

    Kim> While inside one running program (call it A), I want to create another,
    Kim> totally independent, process (call it B), such that process A could exit or
    Kim> be killed and restarted without affecting B in any way.

    Kim> One way I understand to do this is to have A call fork(). Then, the child
    Kim> process, B, should call execv() to execute the desired program.

    Kim> One complication is that process A has several listening sockets as well as
    Kim> a couple other socket connections open at the time it wants to create B. I
    Kim> understand that, upon fork(), process B inherits *copies* of all those open
    Kim> descriptors, and so before proceeding with the execv() call, I should first
    Kim> close() all those open descriptors in process B.

    Kim> BUT, when I do it this way, all of process A's descriptors seem to get
    Kim> closed too, and A can no longer communicate on its sockets. Bad.

  Are you sure that you close them only in B? Post code?

    Kim> On the other hand, if I do NOT close all the descriptors in B, then if A
    Kim> exits and is restarted while B is still alive, then A generates BIND
    Kim> FAILED--ADDRESS ALREADY IN USE errors when it tries to open its sockets.

    Kim>  Other things I have tried:

    Kim> - Using vfork() instead of fork(), but not closing any descriptors. Seems
    Kim> to have the same BIND FAILED problem.

  vfork() doesn't do anything different in that respect.

    Kim> - Making B into a daemon by calling fork() twice, each time having the
    Kim> parent exit. (This comes from  "Unix Network Programming, Vol 1" by W.
    Kim> Richard Stevens.) Even after all this, B still seems to have a hold on A's
    Kim> descriptors.

  Post/email code sample.

]      Out and about in Ottawa.    hmmm... beer.                |  firewalls  [
]   Michael Richardson, Sandelman Software Works, Ottawa, ON    |net architect[
] mcr@sandelman.ottawa.on.ca http://www.sandelman.ottawa.on.ca/ |device driver[
] panic("Just another NetBSD/notebook using, kernel hacking, security guy");  [