我在Linux上有一个相对简单的pthread程序。为此,我把它剥去了一小块,贴在最后。
wait(2)的所有手册页都说wait()将阻止除非使用WNOHANG(甚至不能指定wait())。看看桁架输出,它只是一个不停的重复:
5460 wait4(-1, 0x7f8ee479fea8, 0, NULL) = -1 ECHILD (No child processes)
再次,查看wait4(2)的man页面,它表示返回结果与waitpid()相同,并且waitpid应该阻止,除非有WNOHANG,并且truss显示调用是在选项为0时进行的
供参考,这是:
-
#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;
}
答案 0 :(得分: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.
因此它不会阻塞,因为阻止错误是没有意义的。
答案 1 :(得分:1)
wait()
也会立即返回,值-1
且errno
设置为ECHILD
(这就是您的{{1}告诉你)。在没有子进程存在的情况下,您期望它做什么?