![](/img/trans.png)
[英]Send some arguments (like Ctrl-C, 3, some_string), to program, from bash script
[英]Preventing Ctrl-C from closing program
這是我之前提出的問題的擴展。 覆蓋Ctrl-C
我有這段代碼正在處理ctrl-c的信號,雖然這是在一台機器上運行的,但我在另一台機器上運行了它,但是現在按下ctrl-c之后它再次退出程序。
當我問我的教授時,他告訴我,在處理程序中,我將需要防止進一步處理信號,但是我不確定如何執行此操作。
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include "Input.h"
#include "CircleBuff.h"
sig_atomic_t sigflag = 0;
void catch_int(int sig_num) {
sigflag = 1;
//printf("to do: Print history");
}
void printHistory(CircleBuff hist) {
cout << "Complete History:\n" << endl;
hist.print();
cout << endl;
}
int main(int argc, char** argv) {
signal(SIGINT, catch_int);
//my code here
do {
//more code here
if (sigflag != 0) {
printHistory(history);
sigflag = 0;
}
} while(report != 0); //which is assigned in the code
這是簡化的代碼:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
sig_atomic_t sigflag = 0;
void catch_int(int sig_num) {
sigflag = 1;
printf("to do: Print history");
}
int main(int argc, char** argv) {
signal(SIGINT, catch_int);
do {
} while(1);
}
您是否嘗試過signal(SIGINT, SIG_IGN);
?
我認為那行得通
編輯:
我回過頭來,稍微減少了您的程序,處理程序似乎可以正常工作(每次調用都會增加該標志),但是實際的系統調用(在mycase中為睡眠狀態)被中止了。
您可以重新測試並重述在此減少樣本中不適用於您的內容嗎?
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
volatile sig_atomic_t ctrlCcount = 0;
void catch_int(int sig_num){
ctrlCcount++;
}
int main(int argc, char** argv){
signal(SIGINT, catch_int);
do{
sleep(5);
printf("Ctrl-C count=%d\n", ctrlCcount);
}while(1);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.