Hi,
I have a requirement to write a C program, in which a parent process creates 3 child processes. Each of these three child processes are required to run individual programs and once complete, the parent will then exit.
I've managed to create the parent, and 1 child, which does execute a program called average.
I'm stuck at changing this so that I have 3 childs created and each having a different program run. Any help would be appreciated.
main.c
Code:
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t child_pid;
int status;
pid_t wait_result;
child_pid = fork();
if (child_pid == 0)
{
printf("I am a child and my pid = %d\n", getpid());
execlp("average", "./average", NULL);
printf("Could not execl file average\n");
exit(1);
}
else if (child_pid > 0)
{
printf("I am the parent and my pid = %d\n", getpid());
printf("My child has pid = %d\n", child_pid);
}
else
{
printf("The fork system call failed to create a new process\n");
exit(1);
}
printf("I am a happy, healthy process and my pid = %d\n", getpid());
if (child_pid == 0)
{
printf("This code will never be executed!\n");
}
else
{
printf("I am a parent and I am going to wait for my child.\n");
do {
wait_result = wait(&status);
} while (wait_result != child_pid);
printf("I am a parent and I am quitting.\n");
}
return 0;
}
and the average.c file - which works perfectly fine!
Code:
/* average.c */
/*
Program to calculate the average of n numbers
*/
#include <stdio.h>
#include <stdlib.h>
#define NMAX 100
int main()
{
int n, count;
double avg, d, sum = 0.;
double list[NMAX];
/* Read in value for n */
printf("\nHow many numbers do you want to average? ");
scanf("%d", &n);
/* Check that n is not too large or too small */
if ((n > NMAX) || (n <= 0))
{
printf("\nPlease enter an integer only... program will terminate\n");
exit(1);
}
/* Read in the numbers and calculate their sum */
for (count = 0; count < n; ++count)
{
printf("Enter %d number: ", count + 1);
scanf("%lf", &list[count]);
sum += list[count];
}
/* Calculate and display the average */
avg = sum / (double) n;
printf("\nAverage is %5.2f\n\n", avg);
}
Appreciate any advice. I'm very new to the concept of programming and C, so I apologise in advance if this is a stupid question.
Cheers,
K