tags:

views:

62

answers:

4

I think the title says it all, however, I'll expand a bit.

Is there a difference between having the following code at the begining of program 'progX'

if(daemon(0, 0) == -1)
{
    printf("daemon error: %s", strerror(errno));
}

or running 'progX' via the command: progX & 2>/dev/null 1>/dev/null 0>/dev/null

A: 

daemon chdirs to / daemon closes all fds

so you would need to

cd /
progX ....

for it to be the same

krico
+5  A: 

daemon() does several things:

  • Re-parents the process to init by forking and then exiting the parent. Look in the ps list and you'll see that daemons are owned by PID 1.
  • Calls setsid().
  • Changes directory to /.
  • Redirects standard in, out, and error to /dev/null.

Your redirections handle the last action but not the rest.

John Kugelman
and setsid() and so on.... I'm assuming the OP took care of everything in the daemon() call. A good reference is Steven's 'Adavanced programming in the UNIX Environment' whole chapter on daemons.
jim mcnamara
+1  A: 
progX & 2>/dev/null 1>/dev/null 0>/dev/null

stdin (0) is an input. Not output. Daemon startup should close 0,1,2 - actually all open file descriptors right after it forks off from the parent process. So I don't understand why you want to redirect error messages from daemon startup into /dev/null.

What that does is block any messages you might get from ProgX. Just running ProgX as you wrote it is a better idea.

fprintf(stderr, "daemon error %s\n", strerror(errno));

might be better - errors go to stderr, printf outputs to stdout.

jim mcnamara
A: 

hi all, can any one tell me where daemon() system call is defined ?

sss
It's not a system call, it's a library call(that does several system calls) - it lives in glibc.
nos
are stdin stdout and stderr are separate fot each process , if they are standard why to discard the data ?
sss