I need to write a program that creates a process using pipe().
My first task is to write a parent process that generates four child processes using a function fork().
Once fork()successful, replace the child process with another process rover1, rover2, rover3, and rover4, although they all have the same code.
The function of the processes is as follows.
Each child process initially gets its own number. He receives a new number from the parent. Using the following formula, he creates his own new number as follows and redirects it to the parent:
mynumber = (3 * mynumber + 4 * numberreceived)/7
This process continues until the parent sends a message about a stable system. The parent also has its seed. He gets the numbers of all the children and calculates his new number as follows:
mynumber = (3 * mynumber + numbers sent by all the children)/7
The parent will send this number to all its children. This process will continue until the parent discovers that his number is no longer changing. At this time, he will tell the children that the system has become stable.
This is what I did, but my professor said that I should use exec () to execute the child process and replace the child process with another child process. I am not sure how to use exec (). Could you help me with this.
I join only the first generation of descendants.
int main(void)
{
pid_t rover1, rover2, rover3, rover4;
int parentnumber, mynumber1, mynumber2, mynumber3, mynumber4;
int childownnumber1 = 0, status = 1, childownnumber2 = 0,
childownnumber3 = 0, childownnumber4 = 0, numberreceived = 0;
printf("Enter parent number: ");
printf("%d", parentnumber);
printf("Enter each children number");
printf("%d %d %d %d", mynumber1, mynumber2, mynumber3, mynumber4);
int p1[2], p2[2];
if (pipe(p1) == -1) {
perror("pipe call error");
exit(1);
}
if (pipe(p2) == -1) {
perror("pipe call error");
exit(1);
}
rover1 = fork();
if (rover1 == 0) {
for(; numberreceived != 1; ) {
close(p1[1]);
close(p2[0]);
read(p1[0], &numberreceived, sizeof(int));
if (numberreceived == 1) {
close(p1[0]);
close(p2[1]);
_exit(0);
}
mynumber1 = (int)((3*mynumber1 + 4*numberreceived)/7.0);
printf("\nrover1 number: ");
printf("%i", mynumber1);
write(p2[1], &mynumber1, sizeof(int));
}
}
if (rover1 < 0) {
fprintf(stderr,
"can't fork, child process 1 not created, error %d\n",
errno);
exit(EXIT_FAILURE);
}
}