a c program that forks a child and gets int numbers from the keyboard up to 10 seconds,after 10 seconds stops reading and check if any number is read or not,if nothing is read,it terminates the son otherwise it will print the read numbers on the screen and terminates,it does not show the result.
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<signal.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/errno.h>
int status,j,i=0;
pid_t son1, son2;
int string[20];
char s[5];
void handler(int signum)
{
if(i==0)
kill(son1,SIGKILL);
}
void signal_handler_1(int sig_num)
{
printf("\nI sent the signal SIGUSR1 to my child\n");
}
main(){
son1=fork();
if(son1==0)
{
signal(SIGUSR1 , signal_handler_1);
printf("I'm son1, my id is: %d\n", getpid());
pause();
printf("I'm son1 exitting: %d\n", getpid());
exit(1);
}
if(son1>0){
printf("I'm father, my id is: %d\n", getpid());
signal(SIGALRM,handler);
alarm(10);//how can i terminate the reading process after alarm??
while(fgets(s,5,stdin)!=NULL)
{
sscanf(s,"%d",&string[i]);
i++;
}
for(j=0;j<i;j++)
printf("%d\n",string[j]);
kill(son1,SIGUSR1);
wait(&status);
}
return 0;
}
The parent returns to the while-loop after running the signal handeler for SIGALRM.
Also, like linkdd said, please describe the problem in more detail.
In your code the parent sends SIGKILL to the child and it becomes defunct, i.e. a “zombie” since the parent is stuck. The parent never notices that the 10 seconds have elapsed and reads input forever.
Not the prettiest way, but this will make it work.
Define global
Edit parent signal handeler to set a flag when the alarm has gone off.
The child signal handeler could be like this. It is not good to call printf inside a signal handeler.
Change while loop to check if the signal has been sent. So the parent doesnt get stuck.
Its still pretty messy. The fgets() will most probably require (depending on operating system) an empty line after the signal has been received, because the read() (inside fgets) is restarted by the OS. The parsing of the input is also very fragile.