信号提供了一种机制,通知用户进程发生了这些异常 比如除数为0 ,那么内核就为他发送一个SIGLL信号
按下CURL+C 键 内核发送一个SIGINT 信号
一个发出没有接收的信号叫待处理信号、
进程组
1.每个进程属于一个进程组
2.一个子进程和它的父进程属于一个进程组
3.一个子进程和他的父进程属于一个进程组
获取进程组ID
#include <unistd.h>
#include <stdio.h>
int main(int argc, char **argv) {
printf("%d",getpgrp());
return 0;
}
信号处理问题
1. 待处理信号被阻塞
2. 待处理信号不会排队等待,任意类型最多只有一个待处理新哈
3. 系统调用可以被中断
4.不可以用信号来对其他进程中发生的事计数
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <signal.h>
#include <wait.h>
void handler(int msg){
pid_t pid;
if((pid=waitpid(-1,NULL,0))<0){
printf("error");
exit(0);
}
printf("handler child %d\n",pid);
sleep(2);
return;
}
int main(int argc, char **argv) {
int i,n;
char buf[1111];
if((signal(SIGCHLD,handler))==SIG_ERR){
printf("error");
exit(0);
}
for(int i=0;i<3;++i){
if(fork()==0){
printf("hello from child %d \n",getpid());
sleep(1);
exit(0);
}
}
if((n=read(STDIN_FILENO,buf,sizeof(buf)))<0){
printf("read error \n");
exit(0);
}
printf("Parent processing input \n");
while(1){
}
return 0;
}
解决信号阻塞和不会排队等待的情况
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <signal.h>
#include <wait.h>
#include <cerrno>
void handler(int msg){
pid_t pid;
while((waitpid(-1,NULL,0))>0){
printf("handler child %d\n",pid);
}
if(errno!=ECHILD)
{
printf("error");
exit(0);
}
sleep(2);
return;
}
int main(int argc, char **argv) {
int i,n;
char buf[1111];
if((signal(SIGCHLD,handler))==SIG_ERR){
printf("error");
exit(0);
}
for(int i=0;i<3;++i){
if(fork()==0){
printf("hello from child %d \n",getpid());
sleep(1);
exit(0);
}
}
if((n=read(STDIN_FILENO,buf,sizeof(buf)))<0){
printf("read error \n");
exit(0);
}
printf("Parent processing input \n");
while(1){
}
return 0;
}