waitpid 在信号发送后停止等待

waitpid stops waiting after signal is sent

我目前正在为大学做一个 C 项目。除其他事项外,我应该使用 SIGUSR1 向父进程发出信号。 我现在面临的问题是我还需要等待子进程终止,这样我才能安全地关闭所有东西(删除共享内存等)。

目前我正在使用 sigaction() 响应信号并使用 waitpid() 等待子进程终止(无论如何这就是计划 ^^)。但是当我使用 kill() 向父级发出信号时,waitpid() 停止等待并运行父级的其余部分,即使子级仍然是 运行.

我觉得我遗漏了一些明显的东西,但我想不通。

非常感谢任何帮助, 保持安全

蒂姆

#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,但有时也像16128

根据 POSIX waitpid() documentation:

RETURN VALUE

... If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]. ...

您需要检查 return 值:

int status
do
{
    errno = 0;
    int rc = waitpid(pid, &status, 0);
    if ( rc != -1 )
    {
        break;
    }
}
while ( errno == EINTR );