Project Home
Project Home
Trackers
Trackers
Documents
Documents
Wiki
Wiki
Discussion Forums
Discussions
Project Information
Project Info
Forum Topic - example for fork to create 2 child and spawn usage on QNX 4.24?: (2 Items)
   
example for fork to create 2 child and spawn usage on QNX 4.24?  
I am new to QNX programming can anyone provide sample on fork to create 2 child process and spawn usage




Regards,
K.Kandasamy.
Re: example for fork to create 2 child and spawn usage on QNX 4.24?  
Not as easy as 'an example', but a description.  You need first to build and install a signal handler for 'SIGCHLD'.  
That's how a parent process is notified when a child process shuts down.  When the child dies, the parent gets a SIGCHLD
 signal. The handler calls 'wait' or 'waitpid' in a loop, reaping all dead children whenever *one* of them dies - 
important to do that because if two die at "the same time", you'll miss the second while processing the first.  So when 
a child process shuts down, the handler gets called by the signal, gets all their return status values back, and 
accounts for them.  

The fork part is easy.

int PID = fork();
switch PID {
    case 0:  /* I'm the child */
       do_childs_work();
       break;
    case -1:  /* an error occurred */
       fork_failure_oops();
       break;
    default:   /* I'm the parent */
       store_child_pid_in_array_of_outstanding_kids();
       go_back_to_parents_task();
      break;
}

The signal handler gets the PID back from wait or waitpid, looks it up in the array, and knows that the particular child
 is dead, can decode its status, etc.  Look at manual pages for wait, waitpid, etc.

There's a bit more to it.  The memory that belonged to the parent is inherited by the child - both parent and child have
 access to *the same memory* until one of them changes something.  Then the system diverges it and they each own a 
seperate copy.  So one useful thing is to have the parent read a lot of data into memory and then fork a set of children
 to process pieces of the data.  But the child can not communicate back to the parent unless it does something like open
 a socket or a pipe or something like that.  It goes off on its own and does its thing and then exits.  Once it forks, 
it's on its own. 

There's also 'exec' to consider - that's how the command line itself works.  When you press the enter key on cmd line, 
the shell forks/execs the command you entered.  It's the same, except 'exec' runs a new process totally independent from
 the parent, with no (almost no) inheritance of memory.