2018.08.16

信号(signal)机制Unix系统中最为古老的进程间通信机制,很多条件可以产生一个信号:

1、当用户按某些按键时,产生信号

2、硬件异常产生信号:除数为0、无效的存储访问等等。这些情况通常由硬件检测到,将其通知内核,然后内核产生适当的信号通知进程,例如,内核对正访问一个无效存储区的进程产生一个SIGSEGV信号

3、进程用kill函数将信号发送给另一个进程

4、用户可用kill命令将信号发送给其他进程

#include <stdio.h>                              //当这段程序运行时,ctrl + c就无法
#include <sys/types.h>                          //中断这个程序
#include <unistd.h>
 #include <signal.h>
void print(int m)
{
	printf("helloworld!\n");
}


int main()
{
	signal(2,print);
	
	while(1);
	return 0;
}

无名管道通信:

无名管道用于父进程和子进程间的通信。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>


int main()
{
	pid_t pid;

	pid = fork();
	if(pid == -1)
	{
		perror("fork");
		exit(1);
	}
	else if(pid == 0)
	{
		sleep(1);
		char bu[32] = {0};
		int fd1 = open("wow.txt",O_RDONLY);
		if(fd1 == -1)
		{
			perror("open1");
			exit(1);
		}
		int ret1 = read(fd1,bu, sizeof(bu));
		if(ret1 == -1)
		{
			perror("read");
			exit(1);
		}
		printf("%s\n",bu);
	}
	else
	{	
		int  status;
		char buf[32] = "helloworld!";
		int fd = open("wow.txt",O_WRONLY |O_CREAT | O_EXCL,S_IRWXU);
		if(fd == -1)
		{
			perror("open");
			exit(1);
		}
		int ret = write(fd, buf, strlen(buf));
		if(ret == -1)
		{
			perror("write");
			exit(1);
		}
		wait(&status);	
		close(fd);

	}

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值