I have a parent process that receives user-input that can create child processes and then with further input, manipulate individual child processes.
What should be printing is the following:
New Locker Created: 1
New Locker Created: 2
New Locker Created: 3
New Locker Created: 4
New Locker Created: 5
But instead I receive the following:
New Locker Created: 1
New Locker Created: 2
New Locker Created: 3
New Locker Created: 4
New Locker Created: 5
New Locker Created: 5
New Locker Created: 4
New Locker Created: 5
New Locker Created: 5
New Locker Created: 3
New Locker Created: 4
New Locker Created: 5
And this continues for a few more rows but that's the idea. From what I understand this is because the child process continues to execute as parent has been waiting for the other child processes to finish while receiving new input. Is this correct?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include "locker.h"
#include <signal.h>
#include <stdarg.h>
#define P1_READ 0
#define P2_WRITE 1
#define P2_READ 2
#define P1_WRITE 3
#define NUM_PIPES 2
pid_t this_pid;
int main(){
char buffer[100];
int locker_count = 0;
int fd[2*NUM_PIPES];
int len = 0, i;
pid_t pid_list[100], wpid;
memset(pid_list,0,100);
pid_t this_pid;
struct locker_t new_locker = { .id = 0, .user_id = 0, .locked = 1, .owned = 0};
fflush(stdout);
while(1){
scanf("%s", buffer);
fflush(stdout);
if(strcmp(buffer, "CREATE") == 0){
for(i = 0; i < NUM_PIPES; ++i){
if(pipe(fd+(i*2)) < 0){
perror("Failed to allocate pipes");
exit(EXIT_FAILURE);
}
}
fflush(stdout);
this_pid = fork();
if(this_pid == 0){
//close descriptors we don't need in this process
close(fd[P1_READ]);
close(fd[P1_WRITE]);
len = read(fd[P2_READ], &locker_count, sizeof(locker_count));
//increase by 1
locker_count++;
//create locker
new_locker.id = locker_count;
printf("New Locker Created: %d\n", locker_count);
printf("\n");
write(fd[P2_WRITE], &locker_count, sizeof(locker_count));
//finished. close remaning descriptors
close(fd[P2_READ]);
close(fd[P2_WRITE]);
//need to stop this process for further executing
}
if(this_pid > 0){
//close unneeded descriptors
close(fd[P2_READ]);
close(fd[P2_WRITE]);
write(fd[P1_WRITE], &locker_count, sizeof(locker_count));
//now wait for response
len = read(fd[P1_READ], &locker_count, sizeof(locker_count));
//pid_list[(locker_count-1)] = this_pid;
close(fd[P1_READ]);
close(fd[P1_WRITE]);
fflush(stdout);
while ((wpid = waitpid(this_pid, NULL, 0)) > 0);
}
}
if(strcmp(buffer, "QUIT") == 0){
break;
exit(0);
}
}
}
Thanks for your help :)