


- 2) SIGINT
程序終止(interrupt)信號, 在用戶鍵入INTR字符(通常是Ctrl-C)時發出,用于通知前臺進程組終止進程。
? - 3) SIGQUIT
和SIGINT類似, 但由QUIT字符(通常是Ctrl-\)來控制. 進程在因收到SIGQUIT退出時會產生core文件, 在這個意義上類似于一個程序錯誤信號。
? - 15) SIGTERM
程序結束(terminate)信號, 與SIGKILL不同的是該信號可以被阻塞和處理。通常用來要求程序自己正常退出,shell命令kill缺省產生這個信號。如果進程終止不了,我們才會嘗試SIGKILL。
? - 19) SIGSTOP
停止(stopped)進程的執行. 注意它和terminate以及interrupt的區別:該進程還未結束, 只是暫停執行. 本信號不能被阻塞, 處理或忽略.?



代碼
- 子進程運行到3的時候,會停止,父進程喚醒子進程,子進程接著運行,當子進程到4的時候,中斷退出,所有的進程全部結束
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <wait.h>int main() {pid_t pid = 0;int ret;int i =1;if ((pid = fork()) < 0) {perror("fork error!\n");exit(1);}if (pid == 0) {printf("children pid = %d\n", getpid());//raise(SIGINT)for (i = 1; i < 10; i++) {sleep(1);printf("children printf %d ...\n", i);if (i == 3) {printf("stop!\n");raise(SIGSTOP);//進程停止信號}if (i == 4) {printf("contine\n");raise(SIGINT);//進程中斷信號}printf("本次id = %d\n", i);}printf("children exit!\n");exit(0);} else {printf("children process id = %d\n", pid);printf("father process pid = %d\n", getpid());sleep(5);if ((waitpid(pid, nullptr, WNOHANG)) == 0) {ret = kill(pid, SIGCONT);if (ret == 0)//向子進程發送 繼續運行的信號printf("信號發送成功 %d \n", pid);else {perror("信號發送成功 ");}
// printf("\n");}return 0;}
}


- 前面是要捕捉的信號,后面是針對捕捉的信號對應的處理措施,自己寫的一個函數?


定義自己信號處理函數
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <wait.h>void cancel(int aig){printf("當前程序取消了ctrl+C功能\n");
}
int main() {signal(SIGINT,cancel);while (1){printf("*\n");sleep(1);}return 0;
}


代碼
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <wait.h>void ouch(int aig){printf("OUCH! - I got signal %d\n",aig);
}
int main() {struct sigaction act;act.sa_handler = ouch;//設置信號處理函數sigemptyset(&act.sa_mask);//初始化信號集act.sa_flags = 0;sigaction(SIGINT,&act, nullptr);while (1){printf("Hello World!\n");sleep(1);}return 0;
}
- 輸出結果如下圖所示
- 使用 ctrl + \? 停止?

參考鏈接
- C語言waitpid()函數:中斷(結束)進程函數(等待子進程中斷或
- C語言sigaction()函數:查詢或設置信號處理方式