SIGCHLD造成分段错误,不进入处理程序 [英] SIGCHLD causing segmentation fault, not going into handler

查看:157
本文介绍了SIGCHLD造成分段错误,不进入处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的外壳和在功能上增加我与和放大器在后台运行的进程;.
在我的主要方法,我主要有:

I'm trying to make a simple shell and am adding in functionality to run processes in the background with &. In my main method I basically have:

int main() {
  if (signal(SIGCHLD, handle) == SIG_ERR)
    perror("Cannot catch SIGCHLD");
  pid_t child = fork();
  if (child == 0)
    execvp(command, arguments);
  else {
    if (background == 1) {
       printf("1");
       backgroundList(command, child);
       printf("2"); }
    else 
      waitpid(child, NULL, 0);
  }
}

和我的处理我有:

void handle(int s) {
  printf("a");
  if (signal(SIGCHLD, handle) == SIG_ERR)
    perror("Cannot catch SIGCHLD");
  pid_t pid;
  printf("b");
  while((pid = waitpid(0, NULL, WNOHANG)) > 0) {
    printf("c");
    rmBackgroundList(pid);
    printf("d");
  }
}

我可以把它在前台运行就好了一个过程。运行LS有内容打印到屏幕上,然后在A和B被打印,因为它进入SIGCHLD处理程序,但它不会去为C,因为它已经被侍候。

I can can have it run a process in the foreground just fine. Running "ls" has the contents print to the screen, then "a" and "b" are printed since it goes into the SIGCHLD handler, but it doesn't go to "c" since it's already been waited on.

不过,在后台(LS&安培;)运行的是将打印1和2,有家长回去的提示,那么孩子将打印内容到屏幕上,然后分段错误。它没有打印任何我在处理的信件。

However, running something in the background ("ls&") will print "1" and "2", have the parent go back to the prompt, then the child will print the contents to the screen, then segmentation fault. It does not print any of the letters I have in the handler.

我不明白,为什么SIGCHLD有利于那些已经在等候孩子,但会导致段故障,并甚至从来没有进入处理程序,即没有等待的过程。

I cannot figure out why SIGCHLD is good for children that are already waited on but causes a segmentation fault and never even goes into the handler for processes that were not waited on.

推荐答案

您不继的信号处理程序的规则。不能使用的printf() PERROR()阅读规则,对什么是安全的信号处理程序做的。

You are not following the rules for a signal handler. You can't use printf() or perror(). Read the rules on what is safe to do in a signal handler.

还有的行为信号(取决于它是否是一个BSD或SysV的风格的Unix)的变化。 Linux的改变基于_BSD_SOURCE或_GNU_SOURCE和的presence glibc中它的行为取决于如果你调用的gcc -ansi GCC上的变化 - 性病= C99 的gcc -std = gnu99

Also the behavior of signal() changes depending on if it's a BSD or SysV style Unix. Linux changes its behavior in glibc based on the presence of _BSD_SOURCE or _GNU_SOURCE and that changes depending on if you call gcc -ansi or gcc -std=c99 or gcc -std=gnu99

您真的应该使用的sigaction()而不是信号()

You should really be using sigaction() instead of signal().

这篇关于SIGCHLD造成分段错误,不进入处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆