2012-04-15 51 views
0

我在Linux上有一个相对简单的pthread程序。为此,我已经将它剥离成小片,最后贴出来。wait()不会阻塞,在Linux和pthreads

等待(2)的所有手册页都说wait()将被阻塞,除非使用WNOHANG(甚至不能指定wait())。纵观桁架输出,它只是一个不停重复:

5460 wait4(-1, 0x7f8ee479fea8, 0, NULL) = -1 ECHILD (No child processes) 

再次,看着wait4(2)的手册页,它说,返回的结果是相同waitpid函数()和waitpid函数应该块除非有WNOHANG,和桁架表明呼叫用的选项是0

作为参考提出,这是:

  • 2.6.32-300.3.1.el6uek.x86_64
  • glibc的-2.12-1.47.el6_2.9.x86_64
  • GCC-4.4.6-3.el6.x86_64
  • 编译:GCC -pthread -lpthread -o PTW -Wall ptw.c

-

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



static pthread_mutex_t _lock = PTHREAD_MUTEX_INITIALIZER; 
static pthread_cond_t _sem = PTHREAD_COND_INITIALIZER; 

static void* waiter(void*); 

int main(int argc, char ** argv) { 

    pthread_t thr; 

    if (pthread_create(&thr, 0, waiter, 0)) { 
     perror("pthread_create"); 
     return 1; 
    } 

    pthread_mutex_lock(&_lock); 
    pthread_cond_wait(&_sem, &_lock); 

    return 0; 

} 

void* waiter(void* arg) { 

    while (1) { 
     int status; 
     int p = wait(&status); 
     if (p<0) { 
      perror("wait"); 
      // fprintf(stderr, "wait returned without exited child\n"); 
     } 
    } 

    return 0; 

} 

回答

1

wait()也将立即返回,如果没有子进程来等待,以价值-1errno设置为ECHILD(这是你的strace是显示你)。在没有儿童程序的情况下你期待它做什么?

+0

谢谢。我不太明白man page中“unwaited-for children”的意思。我的期望是,它会阻止,直到有一个退出的孩子(例如另一个线程可能会启动一个可能会退出的孩子)。 – 2012-04-15 06:54:33

+0

为什么它应该等待定时器信号关闭,这将调用一个处理程序,它将'fork()'一个孩子,然后等待那个孩子。 :) – Kaz 2012-04-17 17:37:53

+0

我宁可等待SIGCHLD,如果使用信号:) – 2012-05-22 16:35:54

1

wait()通话按文件记录工作。你正在运行到是ERRORS部分here描述错误条件:

ECHILD (for wait()) The calling process does not have any unwaited-for 
      children. 

    ECHILD (for waitpid() or waitid()) The process specified by pid (waitpid()) or 
      idtype and id (waitid()) does not exist or is not a child of the 
      calling process. (This can happen for one's own child if the action 
      for SIGCHLD is set to SIG_IGN. See also the Linux Notes section about 
      threads.) 

    EINTR WNOHANG was not set and an unblocked signal or a SIGCHLD was caught; 
      see signal(7). 

    EINVAL The options argument was invalid. 

因此,它不会阻止,因为它没有意义的阻塞错误。