Linux 指令碼和程式對SIGINT的處理方案,指令碼通過kill給程式傳遞訊號

來源:互聯網
上載者:User
效能測試中,Tester程式由start.sh指令碼來啟動。現在的需求是:使用者按下ctrl-c,程式能graceful退出,從而不用重啟板子。問題 是:ctrl-c產生訊號SIGINT,但是這個訊號是傳遞給指令碼進程的,不是傳遞給Tester進程的。所以這裡就存在一個訊號傳遞的問題。解決辦法如 下:

1. 在指令碼中加入代碼:

Code: Select all
forward_sigint()
{
    # check out the tester's pid
    testerpid=$(cat /tmp/tester.pid)
    kill -2 $testerpid

    # call analyser and quit
    echo "Calling analyser..."
    ./Analyser/analyser

    echo "Test finished. Thanks."
    rm -f /tmp/tester.pid

    exit 0
}
   
......

# trap control-c signal and forwards it to tester
trap forward_sigint SIGINT

這 樣ctrl-c按下後,函數forward_sigint得到執行。然後這個函數取出tester程式的pid,利用kill命令發送SIGINT訊號給 tester,從而使tester程式graceful退出。注意,這裡的kill命令是shell內建的一個命令,不是/bin/kill程式。也可以 使用/bin/kill程式來發送訊號,效果一樣的。

2. 在Tester程式中添加代碼:

首先在main函數中添加:

Code: Select all
// catch SIGINT interrupt
signal(SIGINT, stop_playing);

// write pid into /tmp/tester to make test script knows our pid
write_pid_to_temp_file();

然後是這兩個函數的實現:

/*
* Write our pid to file /tmp/tester.pid
* This makes start script knows our pid and send SIGINT to us
* when the user pressed ctrl-c
*/
void write_pid_to_temp_file()
{
    FILE *pidfile = fopen("/tmp/tester.pid", "wb");
    char content[10];
    sprintf(content, "%d", getpid());
    fputs(content, pidfile);
    fclose(pidfile);
}

/*
* Stop playing and quit
*/
void stop_playing(int sig)
{
    DEBUG_OUTPUT("Ctrl-C caught, stop playing and quit...");
    // restore the SIGINT handler
    signal(SIGINT, SIG_DFL);

    // make sure the glib mainloop is running
    while (!g_main_loop_is_running(loop))
        wait_seconds(1);

    g_main_loop_quit(loop);
}

OK,就是這樣了。關鍵點就是當程式通過指令碼啟動時,訊號是傳遞給指令碼進程的,不是傳遞給正在執行的程式進程的。所以訊號需要傳遞一下方可。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.