OS X下UNIX環境高級編程(第三版)學習日誌-第一章ChapterI 1.9 信號

1.信號(signal)用於通知進程發生了某種狀況。進程有如下3種處理信號的方式。函數

     (1)忽略信號ui

     (2)按系統默認方式處理,多是終止進程spa

     (3)提供一個函數,信號發生時調用該函數,稱爲捕捉信號code

     終端鍵盤有2種產生信號的方法,中斷鍵(interrupt key:ctrl+c或delete)和退出鍵(quit                                              key:ctrl+\)。進程

2.例程:get

#include "apue.h"
#include <sys/wait.h>
static void sig_int(int);   /*our signal-catching function*/
int
main(void){
    char buf[MAXLINE];/*from apue.h*/
    pid_t pid;
    int status;
    if(signal(SIGINT,sig_int)==SIG_ERR)
        err_sys("signal error");
    printf("%% ");/*print prompt*/
    while(fgets(buf,MAXLINE,stdin)!=NULL){
        if(buf[strlen(buf)-1]=='\n')
            buf[strlen(buf)-1]=0;/*replace newline with null*/
        if((pid=fork())<0){
            err_sys("fork error");
        }else if(pid==0){
            execlp(buf,buf,(char*)0);
            err_ret("couldn't execute:%s",buf);
            exit(127);
        }
        /*parent
         *pid is child process
         */
        if((pid=waitpid(pid,&status,0))<0)
            err_sys("wait pid error");
        printf("%% ");
    }
        void sig_int(int signo){
        printf("interrupt\n%% ");
    }

3.重點內容,signal(SIGNO,void *func(int));須要引用頭文件signal.h,第一個參數爲信號,第二個參數爲一個返回值爲void的函數,做用:捕捉到信號後,使用自定義的函數處理。 it

相關文章
相關標籤/搜索