How can I create an efficient loop that lets 2 child processes work with 2 different files?
I tried using a loop like:
for(i = 0; i < 2; i++){
if((pids[i] = fork()) < 0){
fprintf(stderr, "Something wrong happened creating child n:%d\n", i+1);
exit(EXIT_FAILURE);
}
if(pids[i] == 0){
sprintf(nomefile, "file_figlio_%d.txt", i+1);
fd[i] = open(nomefile, O_CREAT | O_TRUNC | O_WRONLY, 0660);
printf("Write on the file n:%d\n", i);
fgets(buffer, sizeof(buffer), stdin);
write(fd[i], buffer, strlen(buffer));
close(fd[i]);
exit(EXIT_SUCCESS);
}
}
The output is going to be:
./7afebb
HELLO 1
Write on the file n:1
HELLO 0
Write on the file n:0
(empty space to fill file 1)
(empty space to fill file 2)
How can I make it ask me to fill file 1 and only after that fill file 2?
// This is how i corrected the code:
void sig_handler(int sig){
printf("SIGNAL RECEIVED: %d\n", sig);
return;
}
for(i = 0; i < n;i++){
if((pid[i] = fork()) < 0){
fprintf(stderr, "Something went wrong\n");
exit(EXIT_FAILURE);
}
if(pid[i] == 0){
pause();
sprintf(nomefile, "figlio_mag%d.txt", i+1);
fd[i] = open(nomefile, O_CREAT | O_WRONLY | O_TRUNC, 0660);
printf("Write on the file:\n");
fgets(buffer, sizeof(buffer), stdin);
write(fd[i], buffer, strlen(buffer));
close(fd[i]);
exit(EXIT_SUCCESS);
}
}
action.sa_handler = SIG_DFL;
for(i = 0; i < n; i++){
printf("PARENT: Click enter to write on file n:%d\n", i);
getchar();
kill(pid[i], SIGUSR1);
wait(0);
}