linux司機售票員問題

/*
*基於信號處理的司機與售票員進程同步問題
*題目要求: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;
    }
}進程

相關文章
相關標籤/搜索