【发布时间】:2019-06-09 16:26:13
【问题描述】:
我正在研究Linux编程中的进程,有这段代码我看不懂。据我所知,当一个进程被挂起时,它不会收到信号(唤醒它的除外),但是在这段代码中,当父进程运行时,它调用wait,但它仍然打印出计数器,这意味着它收到了 SIGUSR1。谁能解释一下?
我已经知道顺序或者运行是任意的,如果子进程先运行就没有问题,但是如果父进程先运行呢?
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
pid_t pid;
int counter = 0;
int status;
void handler1(int sig){counter ++;
printf("counter = %d\n", counter);
fflush(stdout);
kill(pid, SIGUSR1);
}void handler2(int sig){counter += 3;
printf("counter = %d\n", counter);
exit(0);
}
int main() {
signal(SIGUSR1, handler1);
if ((pid = fork()) != 0) {
pid_t p;
if ((p = wait(&status)) > 0) {
counter += 2;
printf("counter = %d\n", counter);
}
} else {
signal(SIGUSR1, handler2);
kill(getppid(), SIGUSR1);
while(1) {};
}
}
我预计程序会暂停,但每次都运行良好。
【问题讨论】:
-
等待并不意味着被暂停
-
你能解释一下吗,这里是关于
wait的linux手册:The wait() system call suspends execution of the calling thread until one of its children terminates -
"暂停执行" 在这种情况下与发送
SIGSTOP信号时的"暂停进程"不同。您在这里遇到了语言问题。 -
^^ 这个。对于
wait(),“暂停执行”只是描述了普通的阻塞。该过程仍然是可调度的,因此可以接收信号。它的文档指出它可能会因EINTR而失败,这一事实清楚地说明了这一点。