Creating multiple process and simulation in C via fork()
Posted
by Yakup OZDEN
on Stack Overflow
See other posts from Stack Overflow
or by Yakup OZDEN
Published on 2010-04-30T07:12:07Z
Indexed on
2010/04/30
7:17 UTC
Read the original article
Hit count: 456
i want to create multiple process groups which will call different functions.
i write the code below. firstly i want to get following output
./fork 4 5
I am a child: 1 PID: 22330
I am a child2: 1 PID: 22334
I am a child: 2 PID: 22331
I am a child2: 5 PID: 22338
I am a child: 4 PID: 22333
I am a child: 3 PID: 22332
I am a child2: 2 PID: 22335
I am a child2: 4 PID: 22337
I am a child2: 3 PID: 22336
'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void forkChildren (int nChildren) {
int i;
pid_t pid;
for (i = 1; i <= nChildren; i++) {
pid = fork();
if (pid == -1) {
/* error handling here, if needed */
return;
}
if (pid == 0) {
printf("I am a child: %d PID: %d\n",i, getpid());
sleep (5);
wait(NULL);
return;
}
}
}
void forkChildren2 (int nChildren) {
int i;
pid_t pid;
for (i = 1; i <= nChildren; i++) {
pid = fork();
if (pid == -1) {
/* error handling here, if needed */
return;
}
if (pid == 0) {
printf("I am a child2: %d PID: %d\n",i, getpid());
sleep (2);
return;
}
}
}
the code gives me the output
[ozdeny@hyperion ~]$ ./fork 4 5
I am a child: 1 PID: 22330
I am a child: 2 PID: 22331
I am a child: 3 PID: 22332
I am a child: 4 PID: 22333
I am a child2: 1 PID: 22334
I am a child2: 2 PID: 22335
I am a child2: 4 PID: 22337
I am a child2: 5 PID: 22338
[ozdeny@hyperion ~]$ I am a child2: 3 PID: 22336
I am a child2: 1 PID: 22339
I am a child2: 2 PID: 22340
I am a child2: 3 PID: 22341
I am a child2: 4 PID: 22342
I am a child2: 5 PID: 22343
I am a child2: 1 PID: 22345
I am a child2: 2 PID: 22346
I am a child2: 3 PID: 22347
I am a child2: 1 PID: 22349
I am a child2: 2 PID: 22350
I am a child2: 1 PID: 22344
I am a child2: 2 PID: 22352
I am a child2: 3 PID: 22353
I am a child2: 4 PID: 22354
I am a child2: 5 PID: 22355
I am a child2: 3 PID: 22351
I am a child2: 4 PID: 22356
I am a child2: 5 PID: 22357
I am a child2: 4 PID: 22348
I am a child2: 5 PID: 22358
© Stack Overflow or respective owner