Reputation: 517
This is a question about an answer to Praveen Gollakota's answer in another question (is this the way I'm supposed to get around comment privileges?).
His answer to the question of why fork twice is, in essence, to make sure the forked process is not a session leader and thus cannot obtain a tty. He gives this example of a forking process, and shows that the second child is not the session leader (SID after the second fork is not the second child's PID).
1. `Parent` = PID: 28084, PGID: 28084, SID: 28046
2. `Fork#1` = PID: 28085, PGID: 28084, SID: 28046
3. `Decouple#1`= PID: 28085, PGID: 28085, SID: 28085
4. `Fork#2` = PID: 28086, PGID: 28085, SID: 28085
However, you can also see here that after the first fork and before the "decouple" step (I'm assuming this is a call to setsid()
), the child is not the session leader. Therefore my question is why call setsid()
? Why not fork once and exit?
My guess is that this has something to do with the session leader being the controlling terminal (or other grandparent). So a follow up question would be, what happens to a process whose group leader exits, but whose session leader is still alive?
Upvotes: 2
Views: 1549
Reputation: 204758
1. `Parent` = PID: 28084, PGID: 28084, SID: 28046
The program has a controlling terminal at this point.
2. `Fork#1` = PID: 28085, PGID: 28084, SID: 28046
The program still has a controlling terminal at this point. If the parent exited, this child would belong to an abandoned process group. It can setpgid()
to another process group in the same session.
3. `Decouple#1`= PID: 28085, PGID: 28085, SID: 28085
Now the program is in another session, and cannot setpgid()
to switch to a process group in the original session.
4. `Fork#2` = PID: 28086, PGID: 28085, SID: 28085
Reparent to init
.
Upvotes: 0