分叉一个孩子并从键盘获取 int 数字长达 10 秒的 ac 程序,10 秒后停止读取并检查是否读取任何数字,如果没有读取任何数字,则终止子程序,否则它将打印读取的数字屏幕并终止,它不显示结果。
#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;
}