Ask a question about daemon

Programming, for all ages and all languages.
Locked
leetow2003
Member
Member
Posts: 70
Joined: Fri Nov 19, 2010 6:54 pm

Ask a question about daemon

Post 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?
User avatar
bluemoon
Member
Member
Posts: 1761
Joined: Wed Dec 01, 2010 3:41 am
Location: Hong Kong

Re: Ask a question about daemon

Post by bluemoon »

put a line feed on the string or flush the output.
leetow2003
Member
Member
Posts: 70
Joined: Fri Nov 19, 2010 6:54 pm

Re: Ask a question about daemon

Post 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.
User avatar
bluemoon
Member
Member
Posts: 1761
Joined: Wed Dec 01, 2010 3:41 am
Location: Hong Kong

Re: Ask a question about daemon

Post 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.
Locked