/*
*基于信号处理的司机与售票员进程同步问题
*题目要求:SIGINT(表开车),由售票员接收,发送信号SIGUSR1给司机,司机打印run the bus
*SIGQUIT(表停车),由售票员接收,发信号SIGUSR2给司机,司机打印stop the bus
*SIGTSTP(表车到总站),由司机接收,发信号SIGUSR1给售票员,售票员打印get off the bus
* */
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
pid_t pid;
void conductor_handler(int signo);
void driver_handler(int signo);
int main()
{
if((pid = fork()) < 0){ //pid为子进程号
perror("fork error.\n");
}
else if(pid == 0){ //child process conductor
signal(SIGTSTP,SIG_IGN); //conductor进程不接收ctrl-z
signal(SIGINT,conductor_handler);
signal(SIGQUIT,conductor_handler);
signal(SIGUSR1,conductor_handler);
while(1){
pause();
}
}
else{ //parent process driver
signal(SIGINT,SIG_IGN); //driver进程不接收ctrl-c
signal(SIGQUIT,SIG_IGN); //driver进程不接收ctrl-'\'
signal(SIGTSTP,driver_handler);
signal(SIGUSR1,driver_handler);
signal(SIGUSR2,driver_handler);
while(1){
pause();
}
}
return 0;
}
void conductor_handler(int signo)
{
switch(signo)
{
case SIGINT :
kill(getppid(),SIGUSR1);
break;
case SIGQUIT:
kill(getppid(),SIGUSR2);
break;
case SIGUSR1:
printf("Final station ,all get off.\n");
exit(0); //到终点子进程结束
}
}
void driver_handler(int signo)
{
switch(signo)
{
case SIGTSTP :
kill(pid,SIGUSR1);
wait(NULL); //等待子进程先结束,终点已到进程退出
exit(0);
case SIGUSR1 :
printf("bus will run...\n");
break;
case SIGUSR2 :
printf("bus will stop...\n");
break;
}
}进程