【问题标题】:I can't understand sigaction() result我无法理解 sigaction() 结果
【发布时间】:2015-09-28 19:21:01
【问题描述】:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

void handler(int sig)
{
  pid_t pid;
  int status;

  while( (pid = waitpid(-1, &status, WNOHANG)) > 0 )
    printf("%d\n", pid);
}

int main(void)
{
  struct sigaction act;

  pid_t pid;
  int ch;

  act.sa_handler = handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  sigaction(SIGCHLD, &act, 0);

  pid = fork();
  if( pid == 0 ) {
    exit(0);
  }
  else {
    if( (ch = fgetc(stdin)) == EOF )
      printf("EOF\n");
  }
}

你好,我想了解一下sigaction函数。如果我执行这个程序,结果如下。

[process id]
EOF

为什么在处理 SIGCHLD 信号后 EOF 在标准输入缓冲区中?我不知道为什么会这样。或者也许我不知道如何使用 sigaction 功能?

【问题讨论】:

  • 哦,我添加了一个标志选项'SA_RESTART',然后就可以了。这是什么..

标签: linux unix signals system eof


【解决方案1】:

fgetc() 如果文件位于文件末尾,则返回EOF尝试读取字符时出错。在这种情况下,read() 被信号中断是一个错误,sigaction()SA_RESTART 选项可以防止此错误。

要区分 EOF 和错误,请使用 feof()ferror(),或测试变量 errno。对于 EOF 情况,errno 将是 0,对于错误是非零(在这种情况下是 EINTR)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多