I need some help with programming in C, I have a question which wants me to create some arbitrary number of child processes, each of which executes a child process function. The number of child processes is supposed to be supplied as a command line argument, and in the child process function it should run a random number of iterations through a simple loop then print "Child X" where X is provided as an argument. If anyone could help guide me through this that would be awesome!
I tried this but I don't understand how processes work in C.
Amended code
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc, char **argv) {
int counter;
pid_t pid = getpid();
int x = atoi(argv[1]); // Changed (added)
printf("Parent Process, my PID is %d\n", pid);
for(counter=1;counter <= x;counter++){ // Changed
if(!fork()){
printf("Child %d is born, my PID is %d\n", counter, getpid()); // Changed
childprocess(counter);
printf("Child %d dies\n", counter);
exit(0);
}
}
}
void childprocess(int num){
int i = 1;
while(i <= num){
printf("Child %d executes iteration: %d\n", num, i); // Changed
i++;
}
}
Original code
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc, char **argv) {
int counter;
pid_t pid = getpid();
printf("Parent Process, my PID is %d\n", pid);
for(counter=1;counter <= argv[1];counter++){
if(!fork()){
printf("Child %d is born, my PID is %d\n", counter, pid);
childprocess(counter);
printf("Child %d dies\n", counter);
exit(0);
}
}
}
void childprocess(int num){
int i = 1;
while(i <= num){
printf("Child %d executes iteration: %d\n", i);
i++;
}
}