c - 发送信号后,waitpid停止等待

标签 c linux multithreading signals

我目前正在为大学进行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,但有时也类似于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]. ...


您需要检查返回值:
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/

相关文章:

c++ - 如何使用智能指针围绕 C 'objects' 实现包装器?

c - 仅在需要时运行的 Posix pthread 工作线程

PHP cURL - 线程安全吗?

c - 在 C 中操作链表

c - 作者插入不需要的换行符

c - 打入 do while 循环

c++ - 在 Iinux 操作系统(自定义板)上运行的应用程序不会从导出的 LD_LIBRARY_PATH 中读取共享库

c - 自午夜以来的纳秒

linux - 我怎样才能杀死管道后台进程?

c++ - 无法关闭 QThread - 应用程序崩溃