关于信号处理问题:
#include "ourhdr.h"
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
static void sig_cld();
int
main()
{
pid_t pid;
printf("prent1\n");
int a =1,b;
if (signal(SIGCHLD, sig_cld) == SIG_ERR)
perror("signal error");
if ((pid = fork()) < 0) { //这句改成:pid=vfork()之后,异常结束就可以在信号处理函数中得到异常终止状态
perror("fork error");
} else if (pid == 0) { /* child */
sleep(2);
abort(); //异常退出
}
printf("prent2\n");
// pause(); /* parent */
sleep(3);
exit(0);
}
static void
sig_cld(int signo) /* interrupts pause() */
{
pid_t pid;
int status;
printf("SIGCHLD received\n");
if (signal(SIGCHLD, sig_cld) == SIG_ERR) /* reestablish handler */
perror("signal error");
if ((pid = wait(&status)) < 0) /* fetch child status */
perror("wait error");
printf("pid = %d\n", pid);
if(WIFEXITED(status))
printf("normal termination, exit status = %d\n",WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("abnormal termination, signal number =%d%s\n",
WTERMSIG(status));
#ifdef WCOREDUMP
WCOREDUMP(status) ? " (core file.generated)" : ")";
#else
")";
#endif
if (WIFSTOPPED(status))
printf("child stopped , signal number = %d\n",
WSTOPSIG(status));
}
运行结果:
prent1
prent2
SIGCHLD received
pid = 802
Segmentation fault (core dumped) //发生错误
不明白,是为什么??请高手指点阿
------解决方案--------------------if (signal(SIGCHLD, sig_cld) == SIG_ERR) /* reestablish handler */
perror("signal error");
这句是要复位信号处理连接, 这是老式UNIX写法, 现在已经不受用了. 而且还会造成段错误.
现在的用法是:
if (signal(SIGCHLD, SIG_DFL) == SIG_ERR)
perror("signal error");