#include
#include
#include
#include
int main(){int ret;alarm(50);sleep(30);ret=alarm(10);printf("%d\n",ret);pause();printf("I have been waken up.\n");
}
阅读并运行程序并回答以下问题:
问题1:红色部分的含义是什么?此时alarm还剩下多少时间?
发出SIGALRM信号,10s
问题2:蓝色部分的含义是什么?
挂起进程,直到捕捉到一个信号
问题3:程序的运行结果是什么,为什么运行结果中没有最后一个printf语句的输入内容?
因为进程没有被唤醒就被终止了
问题4:请在该程序上添加一个signal()函数捕捉信号,并进行信号处理,使程序显示“I have been waken up”。
#include
#include
#include
#include
int main(){int ret;alarm(50);sleep(30);ret=alarm(10);printf("%d\n",ret);signal(SIGALRM,alarm);pause();printf("I have been waken up.\n");
}
#include
#include
#include
#include
#include
#include
int main(){ pid_t pid; pid=fork(); if(pid<0){ perror("fork() error\n"); } if(pid==0){printf("child process wait for signal!\n"); pause();}else{ sleep(3); kill(pid,SIGKILL); printf("parent process send signal to kill child process!\n"); //waitpid(pid,NULL,0);printf("child process exit!\n"); exit(0); }
}
阅读并运行程序并回答以下问题:
问题1:红色部分的含义是什么?
等待pid退出
问题2:若不添加红色程序会出现什么情况?
运行了多次,没有出现什么情况,可能主进程会先于子进程结束(但我没有运行出这个结果)
要求:使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按ctrl-c键);当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
Child process 1 is killed by parent!
Child process 2 is killed by parent!
父进程等待两个子进程终止后,输出如下的信息后终止:
Parent process is killed!
#include
#include
#include void waiting();
void stop();
void keep_alive();
int wait_mark;int main(){int p1,p2;while((p1=fork())==-1);if(p1>0){while((p2=fork())==-1);if(p2>0){printf("parent\n");wait_mark=1;signal(SIGINT, stop); waiting();kill(p1, SIGINT);kill(p2, SIGINT);wait(0);wait(0);printf("parent process is killed children and exit!\n");exit(0); }else{printf("p2\n");//wait_mark=1;signal(SIGINT, keep_alive);pause();printf("child process2 is killed by parent!\n");exit(0);}}else{printf("p1\n");//wait_mark=1;signal(SIGINT, keep_alive);pause();printf("child process1 is killed by parent!\n");exit(0);}
}
void waiting(){while(wait_mark!=0);
}
void stop(){wait_mark=0;
}
void keep_alive(){
}
阅读并运行程序并回答以下问题:
问题1:红色部分的含义是什么?
接收Ctrl+C
问题2:程序的运行结果是什么?