本文介绍: / 如果接受此信号打印….if(signal(SIGINT, handler) == SIG_ERR){ // 注册SIGINT信号,接受后按handler要求执行,键盘输入Ctrl + C可接受exit(1);if(signal(SIGTSTP, SIG_IGN) == SIG_ERR){ // SIG_IGN即对SIGTSTP忽略exit(1);return 0;

用途:

信号可以直接进行用户进程与内核进程之间的交互

特性:

对于一个进程,其可以注册或者不注册信号,不注册的信号,进程接受后会按默认功能处理,对于注册后的信号,进程会按自定义处理


自定义信号:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

void handler(int arg){
    if(arg == SIGINT){
    	puts("catch the SIGINT"); // 如果接受此信号打印.... 
	}
}

int main(int argc, const char * argv[]){
	if(signal(SIGINT, handler) == SIG_ERR){ // 注册SIGINT信号,接受后按handler要求执行,键盘输入Ctrl + C可接受 
		printf("signal error");
		exit(1);
	}
	
	if(signal(SIGTSTP, SIG_IGN) == SIG_ERR){ // SIG_IGN即对SIGTSTP忽略 
		printf("signal error");
		exit(1);
	}
	while(1){
		sleep(1);
		printf("hello worldn");
	}
	return 0;
}

效果:

在这里插入图片描述


程序发送信号:

上述发送信号是按键给程序发送信号,下面就是进程进程之间发送信号

在这里插入图片描述

有将信号发送给其他进程也有将信号发送给本身

代码:

#include <stdio.h>
#include <signal.h>

int main(int argc, const char * argv[]){
	pid_t pid;
	
	pid = fork(); // 若pid大于0则其为创建的子进程pid 
	
	if(pid < 0){
		printf("fork errorn");
	}
	else if(pid == 0){  
		printf("the child process livingn");
		while(1);
	}
	else{
		sleep(3);
		printf("the parent process onlinen");
		kill(pid, SIGKILL); // 结束子进程
		printf("child be stoped by parentn");
		printf("parent stoped himselfn");
		raise(SIGKILL); // 结束本身 
	}
	return 0;
}

效果:

在这里插入图片描述


闹钟定时:

通过闹钟定时关闭进程

代码:

#include <stdio.h>
#include <unistd.h>

int main(int argc, const char * argv[]){
	unsigned int ret;
	ret = alarm(8);
	printf("ret1 = %dn", ret);
	
	sleep(3);
	ret = alarm(3);
	printf("ret2 = %dn", ret);
	while(1);
	
	return 0;
}

效果:

在这里插入图片描述

原文地址:https://blog.csdn.net/xyint/article/details/134653191

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_694.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注