linux_unix编程手册-信号概述signal函数
關于linux_unix編程手冊的代碼見
https://github.com/zzu-andrew/linux_unix.git
上面由編譯過得代碼可以直接使用或者自己clone之后再使用
改變信號量的處置
在linux手冊中對函數signal的解釋是:
可以看出man手冊對signal的書寫更加的形象,signal返回的是一個 void (*sighandler_t)(int)類型的函數
返回的函數就是之前的信號處理函數,一般使用signal的過程如下:
程序測試過程:
說明,程序中信號處理函數使用printf()函數顯示具體信息,但是在現實的編程環境中是絕對不允許在信號處理函數中使用stdio函數,這里只是將其作為調試的一種手段
為兩個不同的信號建立同樣的信號處理程序:
/*************************************************************************\ * Copyright (C) Michael Kerrisk, 2018. * * * * This program is free software. You may use, modify, and redistribute it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation, either version 3 or (at your option) any * * later version. This program is distributed without any warranty. See * * the file COPYING.gpl-v3 for details. * \*************************************************************************//* Listing 20-2 *//* intquit.cCatch the SIGINT and SIGQUIT signals, which are normally generatedby the control-C (^C) and control-\ (^\) keys respectively.Note that although we use signal() to establish signal handlers in thisprogram, the use of sigaction() is always preferable for this task. */ #include <signal.h> #include "tlpi_hdr.h"static void sigHandler(int sig) {static int count = 0;/* UNSAFE: This handler uses non-async-signal-safe functions(printf(), exit(); see Section 21.1.2) */if (sig == SIGINT) {count++;printf("Caught SIGINT (%d)\n", count);return; /* Resume execution at point of interruption */}/* Must be SIGQUIT - print a message and terminate the process */printf("Caught SIGQUIT - that's all folks!\n");exit(EXIT_SUCCESS); }int main(int argc, char *argv[]) {/* Establish same handler for SIGINT and SIGQUIT. Here we use thesimpler signal() API to establish a signal handler, but for thereasons described in Section 22.7 of TLPI, sigaction() is the(strongly) preferred API for this task. */if (signal(SIGINT, sigHandler) == SIG_ERR)errExit("signal");if (signal(SIGQUIT, sigHandler) == SIG_ERR)errExit("signal");for (;;) /* Loop forever, waiting for signals */pause(); /* Block until a signal is caught */ }發送信號,使用kill一個進程可以向另一個進程發送信號(之所以使用kill作為術語,是因為早期的UNIX實現中大多數信號的默認行為是終止進程)
#include <signal.h>int kill(pid_t pid, int sig);pid參數用于標示一個或者多個目標進程,而sig則指向要發送的信號
kill()系統調用還有另一重功用,將參數sig指定為0(即所謂的空信號),則無信號發送,相反kill()僅會檢查錯誤檢驗,查看是否可以向目標進程發送信號,從另一個角度這意味著,可以使用控信號檢測具有特定進程ID的進程是否存在。若是發送信號失敗,且errno為ESRCH,則表明目標進程不存在,若果調用失敗且errno為EPERM(表示進程存在但是無權向目標進程發送信號)或者調用成功(有權向目標進程發送信號),那么就表示進程存在。
改變信號處置:sigaction()函數
除去signal()之外,sigaction()系統調用是設置信號好處置的另一個選擇;
等待信號:pause()
調用pause()將暫停進程的執行,直至信號處理器函數中斷該調用為止(或者直至一個為處理的信號終止進程為止)。
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的linux_unix编程手册-信号概述signal函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作者:覃海焕(1978-),女,博士,
- 下一篇: linux_unix编程手册--信号处理