Link to home
Create AccountLog in
Avatar of chsalvia
chsalvia

asked on

Daemon behavior (detaching from tty)

This question relates to programming for Linux.  I understand that all programs which run under a bash terminal will exit when the terminal closes, unless they are run in the background by appending an '&' symbol at the command line.

But I assume most serious daemons are programmed to detach from the terminal automatically, i.e. this behavior is coded into the application itself.  When I look at the init.d scripts for many popular daemons, such as Apache for example, I do not see a '&' symbol after the start-stop-daemon command in the init.d script, so I assume these daemons are coded to detach from the terminal.

So I tried to write my application so that it automatically detaches from the terminal.  According to the linux man page, this can be done using ioctl.  As a small test, I tried:

      int fd = open("/dev/tty", O_RDWR);
      if (fd >= 0) {
            int ret = ioctl(fd, TIOCNOTTY, 0);
            if (ret == -1) perror("ioctl");
            close(fd);
      }
      else perror("open");

      // pretend we are a daemon...
      for (;;) sleep(10);

This seems to work, because when I view all running processes, a question mark appears under TTY.  But this still doesn't produce the behavior I would expect from a daemon.  When I execute the program from the bash prompt, it still hangs in the foreground, rather than returning me to the bash prompt.  Why does it do this, when it is no longer associated with the current terminal?
ASKER CERTIFIED SOLUTION
Avatar of ravenpl
ravenpl
Flag of Poland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of omarfarid
Please see:

http://www.hmug.org/man/2/setsid.php

You need to refer to a very good book by W. Richard Stevens "Unix Network Programming" 1st edition or his other book "Advanced Programming in the Unix Environment"

SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
There is actually a function to do all the above - see "man -s 3 daemon"
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account