Is there a difference calling daemon(0,0) from within a program, and launching a program to be in background and redirecting it's output
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 co开发者_开发技巧mmand: progX & 2>/dev/null 1>/dev/null 0>/dev/null
daemon()
does several things:
- Re-parents the process to
init
by forking and then exiting the parent. Look in theps
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.
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.
daemon chdirs to / daemon closes all fds
so you would need to
cd /
progX ....
for it to be the same
精彩评论