2013-10-17 48 views
0

這個程序應該是簡單的並行線程和信號程序不會運行

父只是無限期地等待所有子返回(提示,waitpid函數)。 b。孩子設置了兩個信號處理程序(提示,信號)並進入睡眠5分鐘。 i。第一個信號處理程序偵聽USR1信號,並在收到它之後: 1.創建一個線程(提示,pthread_create)。 a。基本上,線程需要做的就是「打個招呼」,然後睡60秒鐘。二,第二個信號處理程序監聽USR2信號,並在收到之後: 1.銷燬線程(提示,pthread_destroy)。

我的代碼編譯得很好,就在我運行它時,絕對沒有任何反應,甚至沒有我第一次將printf作爲測試。我一直盯着它一個小時,沒有錯誤,所以爲什麼不運行?

編輯︰現在運行,謝謝查理,但是當它創建線程時,它輸出「[線程]睡眠1米[線程]睡1分鐘」,然後結束,它永遠不會等待第二個信號

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <signal.h> 

pthread_t thread; 

void* temp() 
{ 
    printf("[thread] hello professor\n"); 
    printf("[thread] sleeping for 1 minute\n"); 
    sleep(60); 
} 
void handle_USR1(int x) 
{ 
    int s; 
    printf("[signal] creating the thread\n"); 
    s = pthread_create(&thread, NULL, &temp, NULL); 
} 

void handle_USR2(int x) 
{ 
    int s; 
    printf("[signal] destroying the thread\n"); 
    s = pthread_cancel(thread); 
} 

int main(void) 
{ 
    int status = 0; 

    if(fork() != 0) 
    { 
    printf("[parent] waiting.....\n"); 
    waitpid(-1, &status, 0); 
    } 
    else 
    { 
    printf("[child] to create the thread: kill -USR1 %d\n", getpid()); 
    printf("[child] to end the thread: kill -USR2 %d\n", getpid()); 
    printf("[child] setting up signal handlers\n"); 

    signal(SIGUSR1, handle_USR1); 
    signal(SIGUSR2, handle_USR2); 

    printf("[child] waiting for signals\n"); 
    sleep(300); 
    } 
    return (0); 
} 
+0

一個新行添加到最初的printf,使之沖洗等待子進程。或者打電話給fflush。事實上,爲你的所有printfs添加一個換行符可能會說服你實際工作。另外,檢查fork()爲-1是個好主意。 –

+0

@charlie什麼會添加一個換行符呢?它甚至從不打印第一個「hello」 – Cyberhawk94

+0

stdio被緩衝,這意味着發送到stdout的字符不會被刷新,直到看到換行符。試試吧,只需更改printf(「hello」);到printf(「hello \ n」);你會看到。我運行你的代碼,它的工作原理。 –

回答

1

爲所有printf添加一個換行符「\ n」。沒有它,標準輸出不會刷新,它會出現你的程序不工作,即使它是。

此外,檢查fork()失敗是一個好主意。 fork()在失敗時返回-1並設置errno。

1

我在搜索其他東西的時候着手解決了這個問題,並且意識到程序會在SIGUSR1信號處理完成後立即終止。你需要等待你的線程像你發出在pthread_join

void handle_USR1(int x) { int s; printf("[signal] creating the thread\n"); s = pthread_create(&thread, NULL, &temp, NULL); pthread_join(thread, NULL); }