View Full Version : processes created with fork

11-16-2008, 05:38 PM
I want to create a process named D which will create 3 other processes called A, B and C. I am using fork like this example:

int main() {
pid_t pida,pidb,pidc;
pida = fork();
pidb = fork();
pidc = fork();

But my question is how I will discriminate the three processes in my programme. I mean that in the parent process i will have three pid numbers (pida, pidb, pidc) but i won’t know them in advance (The system will give these codes when running the programme). The only think i know is that they will be just positive numbers.
For example if i want to do something in process B i am gonna put an “if” but what i am gonna check to realize that i am in process B before to enter the “if” bronchus?

11-17-2008, 07:04 PM

I believe you are going to get more than three processes... Because you have a fork() called after another, the child process from the first fork() is going to call fork() again, etc. So, I recommend you do the following if you only want three child processes. And to distinguish each of the child processes, use an integer variable.


int main() {

pid_t pid = 1;
int i = 0;

for (; i < 3 && pid != 0; i++) {
pid = fork();

if (pid != 0) { /* this is the parent process */
else { /* child processes */
if (i == 0) { } /* this is the first child process */
else if (i == 1) /* this is the second child process */
else if (i == 2) /* this is the third child process */
else { } /* not valid ? */

Integer 'i' will be unique for each child process because it inherits the parent process at the instant it was spawned.

I haven't been doing fork() programming in a while but this is the concept I would use. Hope this helps.

- member887