BOTCLEAN
ENCORE5
PAUSE
SOMECLEAN
ENCORE1
CLEAN
ENCORE
BOX
SOLUTION
GO
Let us solve this example together!
Step 1 is to establish a clear goal.
The primary goal is to: spawn 5 processes, wait for their
completion and report their exit status.
The secondary goal is to: Learn how to use process control functions.
Let's assume first that the standard I/O file stdio.h will be required ...
#include <stdio.h>
The five processes will be called: proc1, proc2,
proc3, proc4, and proc5. If you want to define and initialize
a character array called process[], what would the first part of
the declaration be? (Don't give the array size, it will be
determined by the initialization values.)
Answer here:
That is correct!
You've got it on the 2nd try.
Good! Now you understand the concept!
Start with char followed by *
Try char *process[]
FORGET1
The correct answer is char *process[]
#include <stdio.h>
char *process[] = {"proc1", "proc2", "proc3", "proc4", "proc5"};
The process counter i, the process status status,
the process id procid and the exit status exitstat
should all be of what type?
Answer here:
That is correct!
You've got it on the 2nd try.
Good!, Now you understand the concept!
It is a type that takes whole numbers.
Try an int or a short
FORGET2
The correct answer is int or short
#include <stdio.h>
char *process[] = {"proc1", "proc2", "proc3", "proc4", "proc5"};
main()
{
int i, status;
int procid, exitstat=0;
:
:
}
Which program segment will fork all 5 processes, and then execute
the child processes? (Remember, fork() returns 0 to the child
process and the process number of the child to the parent.)
a for (i=0; i < 5; i++) {
if ((procid = fork()) == 0)
if (execv(process[i], NULL)== -1)
exit(1); break; }
b for (i=0; i < 5; i++) {
if ((procid = fork()) <> 0)
if (execv(process[i], NULL)== -1)
exit(1); break; } }
c for (i=0; i < 5; i++) {
if ((procid = fork()) == 0)
if (execv(process[i], NULL)<> -1)
exit(1); break; } }
Select one:
That is correct!
You've got it on the 2nd try.
Good! Now you understand the concept!
Think about what fork() returns!
Think about what execv() returns!
FORGET3
The correct choice is a. Choices b and c need to
have <> replaced by ==! Therefore:
#include <stdio.h>
char *process[] = {"proc1", "proc2", "proc3", "proc4", "proc5"};
main()
{
int i, status;
int procid, exitstat=0;
for (i=0; i < 5; i++) {
if ((procid = fork()) == 0) { /* child process */
if (execv(process[i], NULL)== -1)
exit(1);
break; /* if fork fails*/
}
}
The parent process will wait for the child processes and report
the outcome. The algorithm for achieving this is:
if ((procid != 0) { /* then the parent process */
for (i = 1; i<= 5; i++) {
procid = wait(&status);
if (status != 0) {
exitstat++;
printf("PROCESS %d FAILED\n", procid);
}
else
printf("Process %d SUCCESSFUL\n", procid);
}
}
exit(exitstat); /* exit Control Process */