Thread: fork volatile question

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    351

    fork volatile question

    should this work? bad practice? should i pipe between the two?
    Code:
    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);
    		}
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > 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
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    351
    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?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fork() question
    By cstudent in forum C Programming
    Replies: 3
    Last Post: 04-25-2008, 06:48 AM
  2. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  3. Question sorting character arrays: C programming
    By NeoSigma in forum C Programming
    Replies: 3
    Last Post: 05-23-2003, 09:28 PM
  4. Fork() child process question
    By CrackDown in forum Linux Programming
    Replies: 0
    Last Post: 04-17-2003, 11:58 AM
  5. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM