Sujet : Re: Why does getppid() still return old parent pid after setsid()?
De : gazelle (at) *nospam* shell.xmission.com (Kenny McCormack)
Groupes : comp.unix.programmerDate : 09. Nov 2024, 10:25:22
Autres entêtes
Organisation : The official candy of the new Millennium
Message-ID : <vgn9q2$8mls$1@news.xmission.com>
References : 1
User-Agent : trn 4.0-test77 (Sep 1, 2010)
In article <
vgl8h1$385vs$1@dont-email.me>, <
Muttley@DastartdlyHQ.org> wrote:
I've tried this code on both MacOS and Linux yet the child process getppid()
still returns its original parent process instead of "1" for init which is
what I'd expect. Isn't setsid() supposed to completely detach the child or
have I misunderstood?
I suppose the obvious question at this point is: Why do you care? What's
the underlying issue?
I'm not saying that to be snarky (seriously, I'm not!). I am genuinely
curious as to why you are curious. If this is a solely a question of
academic curiosity, then the answer is "because that's the way it is". As
far as I know, in classic Unix, the only way for a process to get
"re-parented" is to have the parent die. Of course, as others have noted,
under Linux, there is also the re-parenting "prctl".
The usual method for ensuring that a process *does* have getppid() == 1 is
the classic "double fork". The parent forks(), the child then forks() and
exits. The grandchild then does the work (either directly or via exec()).
BTW, note that "total isolation" (in your words, "completely detach") is
actually somewhat difficult to achieve and care must be taken to do it
right. Among other things, if you have any terminals open (the usual
stdin/stdout/stderr), then you still have a connection to those terminals
and may receive signals therefrom (e.g., if a user hits ^C on that terminal
or if the terminal is terminated). "sshfs", in particular, is vulnerable
to this problem; unless you take special care, sshfs will terminate if the
shell (terminal window) from which it was launched is exited.
In fact, it is somewhat surprising how many common ordinary day-to-day
programs there are that still do things like this. And by "do things like
this", I mean fail to daemonize correctly.
-- I shot a man on Fifth Aveneue, just to see him die.