In: Computer Science
Code:
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
// function to work with fork
void printer(int n)
{
// forks n processes
for(int i=0; i<n; i++)
{
int pid = fork();
// if it is child then print it's
id
if(pid == 0)
{
printf("%d ",
getpid());
exit(0);
}
// if parent then wait until the
child executes
else
wait(0);
}
// execution of all processes completes
// Note: This line is optional
printf("\nAll childs execution
completed!!");
}
int main(int argc, char const *argv[])
{
// print invalid argument if no.of argumets are
not 2 and given value is not number
if(argc != 2 &&
!isdigit(argv[argc-1]))
{
printf("invalid
argumets");
return 0;
}
// since, first argumets is string we have to
convert it to integer using atoi function
// then pass it to the printer function
printer(atoi(argv[argc-1]));
return 0;
}
Command line argument:
10
Output:
Hope your problem solved and you are appreciating this solution.
Feel free to comment doubts in comment section .