That is my code.
#include <stdio.h>
#include <stdlib.h>
int main ( int argc, char *argv[] )
{
int i, pid;
for(i = 0; i < atoi(argv[1]); i++) {
pid = fork();
if(pid < 0) {
printf("Error");
exit(1);
} else if (pid == 0) {
printf("Child (%d): %d\n", i + 1, getpid());
exit(0);
} else {
wait(NULL);
}
}
}
The output is like that.
Child (1): 5676
Child (2): 4624
Child (3): 4800
Child (4): 5596
Child (5): 5580
However that is not the expect output in the my homework.
It should be like that. What’s wrong with code? Can someone help me?
Child (2): 4625
Child (1): 4624
Child (3): 4626
Child (4): 4627
Child (5): 4628
Thank You for your help. Now I will try it out.
P.S. Sorry my English is bad. I hope you can understand what I said.
Your code work perfectly on my computer. It can be os dependant.
however you should check if argc is not equal to 1 to avoid segmentation fault if no arguments are given to your program.