With daemonize() throwing exception.

I have a function for daemonize() and then I call this to my main(). Here below is my main...

int main(int argc, char **argv)
{
daemonize();
try{
............
if(fail()) throw Exception(...)
.........
}
catch (const Exception& e) {
cout<< (e.toString());
return -1
}

here if try fails it is not throwing the error Exception. I tried by commenting the daemonize() call. Then they throw the error if try fails.
I could not understand why the daemonize() process does not allow the exceptions to throw.
I could not able to get clue, how to throw error without distrubing the daemonize();.
please help.

Can you show us you daemonize() code?

Here is my daemonize code:

void daemonize()
{
fclose(stderr);
fclose(stdin);
fclose(stdout);

switch( fork() ){
case 0:
break;
case -1:
throw FatalException(__FILE__, __LINE__);
default:
_exit(0);
}
setsid();

switch( fork() ){
case 0:
break;
case -1:
throw FatalException(__FILE__, __LINE__);
default:
_exit(0);
}

int fd;
fd=open("/dev/null", O_RDONLY);
if (fd != 0)
dup2(fd,0);
fd=open("/dev/null", O_WRONLY);
if (fd != 0) {
dup2(fd,1);
dup2(fd,2);
}
}

You can't use fclose on stdin, stdout, or stderr. And there's no point in closing them when you're duplicating over them anyway, so just remove those altogether.

This likely isn't related to the error, but open() does not return 0 on error, it returns -1. Check if fd<0.

You should also close the original fd of anything you're duplicating once you're done copying it.

Thanks. This helped.