2013-10-17 45 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); }