Page 1 of 1

Ask a question about daemon

Posted: Mon Mar 11, 2013 9:59 pm
by leetow2003
Look:

Code: Select all

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?

Re: Ask a question about daemon

Posted: Mon Mar 11, 2013 11:52 pm
by bluemoon
put a line feed on the string or flush the output.

Re: Ask a question about daemon

Posted: Tue Mar 12, 2013 2:49 am
by leetow2003
bluemoon wrote:put a line feed on the string or flush the output.
Could you tell me in detail?Or could you write codes?
Thank you very much.

Re: Ask a question about daemon

Posted: Tue Mar 12, 2013 3:09 am
by bluemoon
The problem may be caused by the output being buffered.
You may need to open the file with O_SYNC, or flush it with sync().
btw, for text output it's more convenient to use fopen() which come with fflush(fp), while sync() flush all IOs.
leetow2003 wrote:could you write codes?
No, sorry.