#发信号和捕捉信号
创建子进程代表售票员,父进程代表司机 ,同步过程如下:
售票员捕捉 SIGINT(代表开车),发 SIGUSR1 给司机,司机打印(“let’s gogogo”)
售票员捕捉 SIGQUIT(代表停车),发 SIGUSR2 给司机,司机打印(“stop the bus”)
司机捕捉 SIGTSTP(代表车到总站),发 SIGUSR1 给售票员,售票员打印(“please get off
the bus”)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
pid_t pid;
void driver_handler(int signo);
void saler_handler(int signo);
int main(int argc, char *argv[])
{
if ((pid = fork()) == -1)
{
perror("fork");
exit(-1);
}
if (pid > 0) /* parent driver */
{
signal(SIGTSTP, driver_handler);
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGUSR1, driver_handler);
signal(SIGUSR2, driver_handler);
while (1) pause();
}
else /* child saler */
{
signal(SIGINT, saler_handler);
signal(SIGQUIT, saler_handler);
signal(SIGTSTP, SIG_IGN);
signal(SIGUSR1, saler_handler);
signal(SIGUSR2, SIG_IGN);
while (1) pause();
}
return 0;
}
void driver_handler(int signo)
{
if (signo == SIGUSR1)
printf("Let's gogogo!\n");
if (signo == SIGUSR2)
printf("Stop the bus!\n");
if (signo == SIGTSTP)
kill(pid, SIGUSR1);
}
void saler_handler(int signo)
{
pid_t ppid = getppid();
if (signo == SIGINT)
kill(ppid, SIGUSR1);
if (signo == SIGQUIT)
kill(ppid, SIGUSR2);
if (signo == SIGUSR1)
{
printf("please get off the bus\n");
kill(ppid, SIGKILL);
exit(0);
}
}
查看10道真题和解析