我目前正在为大学进行C项目。除其他外,我应该使用SIGUSR1
通知父进程。
我目前面临的问题是,我还需要等待子进程终止,以便最终可以安全地关闭所有内容(删除共享内存等)。
目前,我正在使用sigaction()
响应信号,并使用waitpid()
等待 child 终止(无论如何,这是计划^^)。但是,当我使用kill()
通知 parent 时,即使 child 仍在运行,waitpid()
也会停止等待并运行 parent 的其余部分。
我觉得我缺少明显的东西,但我无法弄清楚。
任何帮助是极大的赞赏,
注意安全
提姆
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
void handle_sigusr1(int sig) {
printf("Recieved signal %i.\n", sig);
}
int main() {
pid_t pid;
pid = fork();
if (pid == -1) {
perror("fork:");
return EXIT_FAILURE;
}
else if (pid == 0) {
printf("Hello from the child.\n");
kill(getppid(), SIGUSR1);
sleep(3);
printf("Hello again from the child.\n");
return EXIT_SUCCESS;
}
else {
printf("Hello from the parent.\n");
struct sigaction sa;
sa.sa_handler = &handle_sigusr1;
sigaction(SIGUSR1, &sa, NULL);
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
printf("Exit status: %i\n", WEXITSTATUS(status));
printf("Finished waiting for child.\n");
return EXIT_SUCCESS;
}
}
输出:Hello from the parent.
Hello from the child.
Recieved signal 10.
Exit status: 0
Finished waiting for child.
tim@schlepptop:signalTest$ Hello again from the child.
PS:WEXITSTATUS(status)
通常是0
,但有时也类似于16
或128
。
最佳答案
每POSIX waitpid()
documentation:
RETURN VALUE
... If
wait()
orwaitpid()
returns due to the delivery of a signal to the calling process,-1
shall be returned anderrno
set to[EINTR]
. ...
您需要检查返回值:
int status
do
{
errno = 0;
int rc = waitpid(pid, &status, 0);
if ( rc != -1 )
{
break;
}
}
while ( errno == EINTR );
关于c - 发送信号后,waitpid停止等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65852975/