2015-03-13 44 views
1

我在處理信號時遇到問題。我在終端中運行程序,我按了CTRL + C,但沒有看到「我按下CTRL-C」沒有打印。但我想刪除行execl("/usr/bin/gedit", "gedit", "test.c", NULL),「我按CTRL-C」被打印。execl後在C中處理信號

我可以幫助你,如何打印「我按CTRL-C」並解釋它爲什麼。我很感謝你的幫助。非常感謝你。

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <signal.h> 

int loop_forever = 1; 

void on_sigint() 
{ 
    printf("\nI am pressed CTRL-C\n"); 
    loop_forever = 0; 
} 

int main() 
{ 
    printf("My homework\n"); 

    execl("/usr/bin/gedit", "gedit", "test.c", NULL); 
    signal(SIGINT, on_sigint); 
    while (loop_forever) 
    { 
    } 

    exit(1); 
} 

回答

2

execl代替你執行其它程序

基本上,它將您的過程轉換爲gedit過程。您的代碼將不再執行,並且gedit將在其位置運行。

運行另一個從你單獨的程序,您可以使用

if(!fork()) { 
    execl("/usr/bin/gedit", "gedit", "test.c", NULL); 
} 

的詳細說明,請參閱如何this questionfork作品exec在Unix進程模型。

+0

我理解你說的。非常感謝你。 – Hoang 2015-03-13 17:59:11

+0

@ user3168209如果回答您的問題,您可以[標記爲已接受](http://meta.stackexchange.com/a/5235) – 2015-03-13 18:00:29