How do i create a number of child processes given from command line ?
Something like this , where n is given from command line :
for (i = 0; i < n; i++) {
pids[i] = fork();
}
How do i create a number of child processes given from command line ?
Something like this , where n is given from command line :
for (i = 0; i < n; i++) {
pids[i] = fork();
}
No, this will not work because then the child processes will create more children and this will not be what you wanted. For a better idea of how that happens, go take a look at fork() branches more than expected?. So you have to break out of the loop if the current process is a child like so:
for (i = 0; i < n; i++) {
if (!(pid[i] = fork()))
break;
}
In order to see this in action, lets look at minimally complete example
file.c:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int i, n = atoi(argv[1]);
pid_t *pid = calloc(n, sizeof *pid);
for (i = 0; i < n; i++)
if (!(pid[i] = fork()))
break;
puts("hello world");
return 0;
}
Then compile and run it
$ gcc -o file file.c
$ ./file 3
hello world
hello world
hello world
hello world
Note that there are 4 messages because there 3 children plus the parent process.