You are not logged in.

#1 2013-03-12 03:57:59

leetow2006
Member
Registered: 2013-02-13
Posts: 21

Ask a question about daemon

Look:

int main()
{
if(fork())
   exit(0);
  setsid();
  //the second fork
  if(fork())
   exit(0);
  //=========
  int fd=open("/dev/tty",O_RDWR);
  ioctl(fd, TIOCSCTTY, 1);
  while(1)
  {
    sleep(20);
    write(fd,"hello",10);
  }
  //daemon code
}

I am heard if I don't write the second fork,the process can connect
a control terminal,but I find I write the second fork or don't write
the codes,the screen couldn't display the string "hello",Why?
How to correct my codes?

Offline

#2 2013-03-12 04:05:04

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 19,772

Re: Ask a question about daemon

Moderator: Moving to Programming and Scripting


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#3 2013-03-12 22:40:45

deepsoul
Member
From: Earth
Registered: 2012-12-23
Posts: 67
Website

Re: Ask a question about daemon

leetow2006, have you read the manual page daemon(7)?  There a number of steps are given that system daemons should perform.  It says in step 7 that the second fork serves "to ensure the daemon can never re-acquire a terminal again."  So this seems to be a precautionary step, just in case.  Detaching from the terminal is done before that with setsid(), so ditching a controlling terminal seems unrelated to stdin/out and more related to the process hierarchy.  I am no expert, but my guess is that the daemon might be killed when the terminal exits if it does not detach, and might even be brought back  into the foreground and killed with Ctrl-C for example.  You don't want that for a daemon.


Officer, I had to drive home - I was way too drunk to teleport!

Offline

Board footer

Powered by FluxBB