7 信号通信2

0. 信号通信框架:

信号发送:kill、raise、alarm

信号接收:pause()、sleep、while(1);

信号处理:signal


1. 信号的发送函数:

kill:发送信号给任意进程

raise:只能发送给当前进程,等于kill(getpid(),sig)

alram:发送闹钟信号


2. kill函数:

头文件: #include <signal.h>

#include <sys/types.h>

函数原型: int kill(pid_t pid, int sig)

参数: pid: 正数,要接收信号的进程号;

0,信号被发送到与pid进程相同的进程组中;

-1,信号发送给所有的进程表中的进程

sig: 信号

返回: 成功0,错误-1

3. raise函数:

头文件: #include <signal.h>

#include <sys/types.h>

函数原型: int raise(int sig)

参数: sig,信号

返回: 成功0,错误-1


4. 实例 rasie函数:

#include "stdio.h"
#include "sys/types.h"
#include "signal.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{ 
  printf("raise before");
  raise(9);// _exit()    exit()
  printf("raise after\n");
  return 0;
}
执行结果:

alex@alex-virtual-machine:/extra/process/007$ gcc raise.c
alex@alex-virtual-machine:/extra/process/007$ ./a.out
Killed
alex@alex-virtual-machine:/extra/process/007$

5. 示例二:子进程收到信号后会进入Stop状态,8s之后父进程杀死子进程,并通过wait函数会回收资源,使子进程不会进入僵死状态

#include "stdio.h"
#include "sys/types.h"
#include "signal.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
  pid_t pid;
  pid=fork();
  if(pid > 0 )	//parent
  {
    sleep(8);
	if(waitpid(pid,NULL,WNOHANG) == 0)
	{
	  kill(pid,9);
	}
	wait(NULL);
	while(1);
  }
  if(pid ==  0)	//child
  {
   printf("raise function before\n");
   raise(SIGTSTP);
   printf("raise funtion after\n");
   exit(0);
  }
  return 0;
}

执行结果:

开始执行时:

 4117  4566  4566  4117 pts/6     4566 S+    1000   0:00 ./a.out
 4566  4567  4566  4117 pts/6     4566 T+    1000   0:00 ./a.out
 4044  4568  4568  4044 pts/5     4568 R+    1000   0:00 ps -axj
alex@alex-virtual-machine:/extra/process$

8s之后:

 1991  4530  1991  1991 ?           -1 S      130   0:00 pickup -l -t unix -u -c
 4117  4566  4566  4117 pts/6     4566 R+    1000   0:25 ./a.out
 4044  4573  4573  4044 pts/5     4573 R+    1000   0:00 ps -axj
alex@alex-virtual-machine:/extra/process$



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值