關於Linux訊號的備忘錄

2021-08-20 21:02:46 字數 2205 閱讀 4441

最近在做乙個動態日誌模組,需要用到linux訊號,雖然用到的有關訊號的東西都比較簡單,但是我感覺還是要系統的學一下訊號,為加強理解和今後便於記憶,寫了下學習和使用中的一些備忘錄。

有時候對於某些程式,我們不知道何時停止他們執行,只是在他們執行過程中我們達到了我們需要的結果我們才讓他們停止執行,這樣的程式我們一般是寫乙個while(true)的迴圈,當然我們終止他們直接是強制殺死程序,現在我們用訊號來讓他們更優雅的退出,在他們執行過程中,向他們傳送乙個訊號,程式接收到訊號後停止while迴圈,然後優雅的退出,我們這邊使用sigusr1訊號,**如下:

#include 

#include

#include

static

void sig_usr(int);

static

volatile

int g_stop = 0;

int main(void)

while(!g_stop)

printf("process exit\n");

return0;}

static

void sig_usr(int signo)

採用ps命令獲得程式的程序號,然後傳送usr1訊號,命令如:kill -s usr1 10120

我們可以通過pause函式去等待乙個訊號的到來,這個函式會一直阻塞,直到有訊號到來,採用這個函式相對於定期檢測更省cpu,上述**檢測程序退出我們可以這樣寫:

#include 

#include

#include

static

void sig_usr(int);

static

volatile

int g_stop = 0;

int main(void)

while(!g_stop)

printf("process exit\n");

return0;}

static

void sig_usr(int signo)

但是這樣會有一些風險,假如訊號正好在while判斷和pause函式之間到來,那麼等到pause函式執行的時候就無法捕捉到訊號了,解決這個問題可以用sigsuspend函式,在執行sigsuspend函式之前先阻塞掉我們要捕獲的訊號,sigsuspend函式執行兩個動作,解除訊號阻塞,等待訊號到來,這兩個動作結合成乙個原子操作,也就是兩個動作的間隙是不會有其他訊號來干擾的,實現**如下,為簡單明瞭,以下省去了一些返回值處理。

#include 

#include

#include

static

void sig_usr(int);

static

volatile

int g_stop = 0;

int main(void)

sigprocmask(sig_setmask, &maskblocked, &maskold);

while(!g_stop)

sigprocmask(sig_setmask, &maskold, null);

printf("process exit\n");

return0;}

static

void sig_usr(int signo)

#include 

#include

#include

#include

void *func_wait_signal(void *arg)

int main(void)

pthread_create(&thread, null, func_wait_signal, &sigset);

pthread_join(thread, null);/* 等待執行緒退出 */

printf("process exit\n");

return

0;}

注意:sigsuspend和sigwait都是接收乙個訊號集作為引數,但是兩者的處理是有區別的,sisuspend是將訊號集中沒有包括的項給他unblock,當訊號集中不包含的訊號到來時sigsuspend才會返回,傳給sigwait的訊號集是當訊號集中的訊號到來時sigwait才返回,該訊號集在傳遞給sigwait之前應當使用sigmaskproc阻塞掉,且sigwait不會改變訊號集掩碼。

linux備忘錄手冊

一些常用的基本命令 uname a 檢視核心版本 ls al 顯示所有檔案的屬性 pwd 顯示當前路徑 cd 返回上一次目錄 cd 返回主目錄 date s 設定時間 日期 cal 顯示日曆 cal 2006 bc 計算器具 man info 幫助手冊 locale 顯示當前字型 locale a ...

linux 備忘錄一

今天學到的東東 1 檢視程序所對應可執行程式的絕對路徑 1 ps ef grep 程序名 獲得pid 2 進入proc檔案系統裡對應的目錄 proc 3 ls l exe鏈結對應的就是可執行檔案的全路經 2 辨別是軟鏈結還是硬鏈結 ls li 檢視檔案對應的inode編號,一樣的則是硬鏈結,軟鏈結通...

linux命令備忘錄

openssl 提供常用密碼演算法 常用的金鑰和證書封裝管理功能及ssl協議的工具 例子 用sha1演算法計算檔案file.txt的雜湊值,輸出到stdout openssl dgst sha1 file.txt chage 修改使用者密碼過期資訊 lastb 讀取位於 var log目錄下,名稱為...