簡體   English   中英

為什么父進程在處理信號后沒有返回到確切的位置?

[英]Why doesn't parent process return to the exact location after handling signal?

#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

sig_atomic_t child_exit_status;

void clean_up_child_process (int signal_number)
{
  /* Clean up the child process.  */
  int status;
  wait (&status);
  /* Store its exit status in a global variable.  */
  child_exit_status = status;
}

int main ()
{
  /* Handle SIGCHLD by calling clean_up_child_process.  */
  struct sigaction sigchld_action;
  memset (&sigchld_action, 0, sizeof (sigchld_action));
  sigchld_action.sa_handler = &clean_up_child_process;
  sigaction (SIGCHLD, &sigchld_action, NULL);

  /* Now do things, including forking a child process.  */
  /* ...  */
  pid_t t = fork();
  if (t!=0) {
      // parent
      sleep(30);    // After handling signal, why does it not continue to sleep 20 (30-10) more seconds?
      printf("Parent exits\n");
  }
  else {
      // child
      sleep(10);
      printf("child exists\n");
  }

  return 0;
}

我得到的結果是10秒鍾后,子進程和父進程都會打印出其消息,然后退出。 我期望的是子進程首先打印出消息,然后父進程將在打印消息並退出之前再休眠約20秒鍾。 為什么父進程在處理20秒鍾以上的睡眠信號之前不恢復到“精確位置”? 有沒有辦法可以做到這一點?

sleep(3)不會重新啟動。

返回值:如果請求的時間已經過去,則返回零; 如果調用被信號處理程序中斷返回睡眠狀態的秒數。

因此,您應該檢查返回值並再次休眠。 像(未經測試的):

rc = 30;
while ((rc = sleep(rc)))
    ;

考慮到您可能想中斷阻塞操作/ select() / poll() / sleep() 一種方法是發送信號,這可能導致當前函數通過EINTR退出。

有一個SA_RESTART標志,該標志使某些函數在接收到信號后重新啟動,主要是read()write() 其他功能的行為取決於實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM