2
votes

How can a process (in my case session leader) get controlling terminal?

What I do in my program:

1. fork;
2. parent -> while(1) or smth. similar;
3. child  -> setsid();
             exec "man ps";

I beleived that i would get nothing in the output. (child is a session leader and therefore now it has no relation to old tty) But i got and don't understand why. Man ouputs. But is not interactive. When I press Ctrl-z it becomes interactive when i press 'q' it quites and returnes to my prog(parent). So the questions are:

  1. Please explain what happens at the beginning (why I have to press ctrl-z, read above)
  2. Why man does some output in that shell?
  3. How can man do it without any tty connected (I checked it with ps, man and pager have "?" in TTY column)
  4. And finally: how can a new session leader acquire a controlling terminal. Are there any wayes besides open(/dev/tty) ?
1

1 Answers

3
votes

Q. 1. to 3.: The child process keep access to stdin, stdout etc., even after setsid(). You need to close them explicitly (or reopen using eg. open("/dev/null",O_RDWR);).

Q 4.:

When a session-leader without a controlling-terminal opens a terminal-device-file and the flag O_NOCTTY is clear on open, that terminal becomes the controlling-terminal assigned to the session-leader if the terminal is not already assigned to some session

http://uw714doc.sco.com/en/SDK_sysprog/_The_Controlling-Terminal_and_Pr.html