All that is needed is the Command in Unix and the output (1) Write a Unix progra
ID: 3747203 • Letter: A
Question
All that is needed is the Command in Unix and the output
(1) Write a Unix program that does the following
You run the program in command line using the following syntax:
you_program_name N
Where N is a number
When the program starts, it does the following
1) If N is not specified in the command line, or the parameter is not a number, or if there are too many parameters, display the correct usage and then exit.
2) It forks three (3) child processes
2a) The main process then enters N loops that repeatedly displays
one line of information like "This is the main process, my PID is ...."
then pauses for about 2 seconds, then displays the above information again
2b) Each of the three child processes repeatedly displays one line of information
like "This is a child process, my PID is ..., my parent PID is ...",
then pauses for about 2 seconds, then displays the above information again, for a total of N times.
Explanation / Answer
#include <stdio.h>
#include<string.h>
int main(int argc,char **argv)
{
int i,pid,ppid,j;
if(argc<2)
{
printf("Usage:./a.out N ");
return -1;
}
if(argc > 2)
{
printf("There are too many parameters ");
return -2;
}
for(i = 0; i < strlen(argv[1]);i++)
{
if( argv[1][i] >=48 && argv[1][i] <=56)
{
continue;
}
else
{
printf("Command line arg N does not contain number ");
return -3;
}
}
ppid=getpid();
for(i = 0; i < atoi(argv[1]);i++)
{
//create three child
for(j = 0; j < 3; j++)
{
pid = fork();
if(pid > 0 )
{
if(getpid() == ppid) //parent process
{
printf("This is the main process, my PID is: %d ",ppid);
sleep(2);
}
}
else
{
if(getppid() == ppid)
{
printf("This is a child process,my PID is: %d ",getpid());
sleep(2);
}
}
}
}
return 0;
}
----------------------------------------------------------------
//output
This is the main process, my PID is: 5
This is a child process,my PID is: 6
This is the main process, my PID is: 5
This is a child process,my PID is: 7
This is the main process, my PID is: 5
This is a child process,my PID is: 100
This is a child process,my PID is: 7