PDA

View Full Version : fork volatile question



rotis23
04-07-2004, 04:57 AM
should this work? bad practice? should i pipe between the two?


static volatile sig_atomic_t init_ok = 0;

...

switch (pid = fork())
{
case -1:
init_ok = -1;
perror("Fork error!");
exit(EXIT_FAILURE);
case 0:
...
//do init stuff here - set init_ok to -1 if any errors
...
for(;;)
{
init_ok = 1; //everything ok - tell parent to exit ok
...
//do loop stuff
...
}
break;
default:
while(init_ok == 0)
{
sleep(1);
}

if(init_ok == 1)
{
exit(EXIT_SUCCESS);
}
else
{
exit(EXIT_FAILURE);
}
}

Salem
04-07-2004, 06:41 AM
> should this work?
No.
fork() creates an exact copy (except for the value stored in pid) of the memory, so each process has their own copy of init_ok. Updates to one do NOT affect the other, no matter how volatile or atomic they are.

The usual way to communicate status is
exit( status ); // in the child

waitpid( pid, &status ); // in the parent

rotis23
04-07-2004, 07:31 AM
Thanks for that.

Seems that that solution will require the child and parent to exit at the same time.

I'm implementing a linux daemon where the parent starts and exits straight away.

The startup script listens for the exit status of the parent before returning OK or FAILED, so it can't wait for the child to exit.

I just want it to wait until the child is waiting for accept (2) (it's a server) so that it can return an error if there is a socket, bind setsockopt failure for eaxmple. There are some other initialisations that have to occur in the child thread.

Seems like pipe is my only option?