Ho cercato di capire se questo è possibile nel modo in cui l'ho fatto o no. Questo programma dovrebbe eseguire il fork di un processo figlio che esegue il looping della stampa su STDOUT e il genitore dovrebbe uscire per restituire il prompt del terminale. Il bambino dovrebbe quindi attendere che SIGINT dica quando chiudere. Tuttavia ricordo di aver letto che SIGINT è inviato solo ai processi in primo piano, il che spiega perché il mio bambino abbandonato non è influenzato da CTRL + C. Esiste un modo per far sì che il bambino abbandonato possa ricevere un segnale inviato dal terminale o qualche chiamata di sistema nel terminale per portarlo in primo piano dove può ricevere SIGINT? O la mia ricerca è senza speranza?Problemi durante l'invio del segnale al processo figlio in C
Codice:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
/* signal handler for the child process */
void catchInt (int signum)
{
printf("\nMy sincerest apologies, master\n");
exit(0);
}
/* signal handler for the parent process */
void ignoreInt (int signum)
{
/* prevent any extra output from being printed */
fflush(stdout);
/* wait for child to apologize before replying */
wait(NULL);
printf("You're welcome\n");
exit(0);
}
/* signal handler for the child's alarm */
void catchAlarm (int signum)
{
printf("It's great to be alive\n");
/* reset the alarm */
signal(SIGALRM, catchAlarm);
alarm(3);
}
int main() {
pid_t pid;
/* fork process */
pid = fork();
if (pid < 0) /* error handler */
{
fprintf(stderr, "Fork Failed");
exit(-1);
}
/* child */
else if (pid == 0)
{
printf("It's great to be alive\n");
/* catch SIGINT and handle as the child should */
signal(SIGINT, catchInt);
/* catch SIGALRM being sent by alarm() */
signal(SIGALRM, catchAlarm);
/* set alarm for 3 seconds */
alarm(3);
for (;;)
{
printf("I have 42001 children and not one comes to visit\n");
usleep(500000);
}
}
/* parent */
else
{
/* exit to abandon child process in the background */
exit(0);
}
return(0);
}
In realtà funziona perfettamente! Dovrò esaminare di più i gruppi di processi. Grazie! – JKomusin
@ JKomusin: Non è davvero una soluzione perfettamente robusta, vedi aggiornamento. – caf