I am new to C , So i only know simple functions.(ex: wait(NULL) ).
Here is my main question :
Modify the program so that only the parent process creates 3 child processes, and each new created process calls a function CPU(). In addition, make the parent process wait for each child’s termination.
I know this one is the correct answer
#include<stdio.h>
int main(void)
{
int i ;
for( i = 0; i < 3; i++)
{
int ret = fork();
if(ret == 0){
printf("My process ID is %d\n", getpid());
return 0;
}
}
for (i = 0; i < 3; i++) //Line B
wait(NULL);
}
but my problems are
why below code is wrong when wait is executed by the parent in the loop
#include <stdio.h> int main(void) { int i ; for( i = 0; i < 3; i++) { int ret = fork(); if(ret == 0) { printf("My process ID is %d\n", getpid()); return 0; } else wait(NULL); } }
in very first code why do we write
wait(NULL)
inside a for loop? can't we write it without a for loopif there is no "return 0" in child process, should the for loop be changed to
for (i = 0; i <7; i++) wait(NULL);
I don't know how to write the
CPU
function