UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2008-11-17 03:33 AM

lvasilis22
Member
Registered: 2008-11-17
Posts: 8

Re: processes using fork

I want to create 3 child processes using fork. So i have used this code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main()
{ 
int i;
for (i=1;i<=3; i++) {
if (fork()==0) {
printf("Child process #%d with ID:%d created from parent process\n",i);
break; } }
}

The three child processes that i want are being created and everything is ok. But i don't know after this code how i am gonna separate the 3 child processes. For example if i want to put some code only for the first child process and not for the others how can i do that. I must put something (a number e.t.c) in order to refer in a spesific child from these that i have created?
I know that every child will have an ID as the parent process has an ID but can i use it to refer to each process in my programme? And if i can how can i do this?

Offline

#2 2008-11-17 04:28 AM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: processes using fork

for (int i=0; i<3; i++)
{
   if (fork() == 0)
   {
      switch(i)
      {
         case 0:   CallSomeFunction();  break;
         case 1:   CallSomeOtherFunction(); break;
         case 2:   CallYetAnotherFunction(); break;
      }
   }
}

Offline

#3 2008-11-17 04:29 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: processes using fork

Just don't create the children in a loop like that if they need to do different things.
I'd make three functions, one per child, which do the fork and the child specific
stuff. Then call the three functions and everything makes sense. If there is a lot
similar work done by all three functions, make a helper function for that and call
it from the child specific functions.

There are other ways of course, but the main thing is to organize your code in such
way that you don't create problems like this at all.

Offline

#4 2008-11-17 02:07 PM

lvasilis22
Member
Registered: 2008-11-17
Posts: 8

Re: processes using fork

You helped me a lot. Thank you!

Offline

Board footer

Powered by FluxBB