CS 330 Prog 1: Basic Forking Your program, \"prog1.c\", will demonstrate the use
ID: 3757126 • Letter: C
Question
CS 330 Prog 1: Basic Forking Your program, "prog1.c", will demonstrate the use of the fork and wait system calls on Unix/Linux machines. The program should perform exactly 12 "runs" before terminating. In each run, the program will create 26 child processes (say pA, pB,.. , pY, pZ). Each process will print its character (A', 'B', , Y', 'Z') once without newline before exiting, that's all the children will do. After creating the 26 children in each run, the parent (original process) will "wait" until all its 26 children have finished, then it will print a newline before going on to the next run or exiting. The output of this program, when properly implemented, will exemplify the unpredictable order in which the processes are scheduled to run. Do not have 26 explicit calls to the fork() function in your code... use looping wisely and you only need a single instance of the fork) call in your program. The two examples below are the output of the instructor's solution. If you've done the assignment correctly, your output should look similar, the formatting at least should be identical BADFHGIEMJKRLCVPOXQUNYZWST ABDEGFHKJILMPNOQSTRVUWCXZY ABEGFHIKJLMPOTRUVCSWXYDZQN ABCFHGILNMDOTEPWYUSZVQRXKJ ABCDFEGIJLKMNOQPRSTUWVZXYH ABDEGH3ILKNMPORQUSTZVYXWCF BACDFEGHLMJNOQPSRTVUWYXZIK ABCDEFGHIJKMNOPQRSUTVWXYLZ ABEDFGHIJMKNLOPRQSCTVUWXYZ ABEDGFJILKMONPUQTYVRHSWCZX ABCDEGHIKMLNOQPSRVXUTJWYFZ ABDEGFHJILKNMPOSQRUTVXWCYZ ABDCGHEIJFKSLRVWQXUTPYNOZM BADCEHFGJIKMLNQOPTVURWSZXY ABDCEFHGJIMLKNQOPSTRVWYXUZ ABCDGFHEJILMKNOQRPSUWTYVXZ ABDEFGIHLJMKONQPTRSUVWCYXZ ABCEFGIHJMNOPQRTSVUDXYWZKL CAFDJKGLNOMPQRTISWHYEXBUVZ ABEFGJIKLNOMPQRYWZVXUTDHSC ABCDFGHIJLKMONPQRTSUXVWYEZ ABCDFGIHJLKNPMORQUSTVWEYXZ ABCEFGHIJLMKONQPSRTUVXYWDZ ABCDEFGIJKMLNPOQSRTUWVXYHZ Hint You do NOT need to track all 26 child PIDs to wait for them individually to complete. The wait (NULL) call completes when any single child terminates, returning the PID of the child. If no children are there any more to be "waited" on, wait (NULL) returns -1. Waiting in a loop until -1 is returned will allow you to pause until all children have completed and have been reapedExplanation / Answer
C Program:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void forkprocess()
{
int procid,i;
for(i=0; i<26; i++){
procid = fork();
if(procid == -1){
}
else if(procid == 0){
printf("%c",i+'A');
sleep(1);
exit(0);
}
}
for(i=0; i<26; i++){
wait(NULL);
}
return;
}
int main(){
int l;
for(l=0;l<12;l++)
{
forkprocess();
printf(" ");
}
return 0;
}