I will write shortly what i want to do with my code and what's the real output. I have a parent process which creates two child processes. Each of the two process read 100 bytes from a different file, child 1 read from "child1.txt", child 2 read from "child2.txt". I want to force to execute child 2 before child 1 through the use of signals.
I created the two child process and paused them (pause end when they receive a signal). So I sent a signal to the child 2, then i sent a signal to the child 1. In this way I expect they will do what i want but they don't (it shows always child1.txt content)and i do not understand why.
This is the code
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <wait.h>
void my_handler(int signo);
int main(int argc, char *argv[]){
signal(SIGCHLD,my_handler);
pid_t pid[2]; //here is where I save child pid
char buffer[100];
for (int i=0;i<2;i++){
if((pid[i]=fork())==0){
signal(SIGUSR1,my_handler);
int fd,nbyte;
pause();
if(i==0){
fd=open("Child1.txt",O_RDONLY);
}else{
fd=open("Child2.txt",O_RDONLY);
}
nbyte=read(fd,buffer,100);
buffer[nbyte-1]='\0';
write(STDOUT_FILENO,buffer,strlen(buffer));
exit(1);
}
sprintf(buffer,"Child %d\n",(int)pid[i]);
write(STDOUT_FILENO,buffer,strlen(buffer));
}
kill(pid[1],SIGUSR1); //I send a signal to unpause child2
wait(NULL); // wait child 2 to terminate
kill(pid[0],SIGUSR1); //unpause child 1
wait(NULL); // wait child 1 to terminate
}
void my_handler(int signo){
}