In my case I'm trying to write to frame buffer /dev/fb1. As soon as I daemonize the program I get no valid file descriptor. I tried it with a regular file (with correct permissions) - same result. When I comment out daemonize(); everything runs fine.
int fbfd;
void initFB()
{
fbfd = open("/dev/fb1", O_RDWR);
if (!fbfd)
{
exit(EXIT_FAILURE);
}
...
}
int daemonize()
{
pid_t pid,sid;
int lockFile;
char ProcessID[10];
pid = fork();
if (pid < 0)
{
exit(EXIT_FAILURE);
} else if (pid != 0)
{
exit(EXIT_SUCCESS);
}
umask(0);
sid = setsid();
if(sid < 0)
{
exit(EXIT_FAILURE);
}
lockFile = open("/var/run/program.pid",O_RDWR|O_CREAT,0640);
if (lockFile < 0)
{
exit(EXIT_FAILURE);
}
if (lockf(lockFile,F_TLOCK,0)<0)
{
exit(EXIT_SUCCESS);
}
sprintf(ProcessID,"%d\n",getpid());
write(lockFile,ProcessID,strlen(ProcessID));
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
signal(SIGCHLD,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGHUP,signal_handler);
signal(SIGTERM,signal_handler);
return(1);
}
int main(int argc,char **argv)
{
daemonize();
initFB();
...
}
Your check for the result of open()
is incorrect. On failure, open()
returns -1
, not 0
. In your case, this happens because open()
will end up with the lowest available file descriptor, which is 0
here, as you've closed stdin
.