FIFO读写产生SIGPIPE信号

以前一直在听说产生SIGPIPE信号,我但我平时遇得少,没怎么管它,今天一小心就遇到

先看代码吧

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#define FIFO_FN   "/tmp/test"

void catch_pipe(int n) {
	printf("signo:%d\n", n);
}

int main() {
	signal(SIGPIPE, catch_pipe);
	if ((mkfifo(FIFO_FN, S_IRWXU | S_IRGRP | S_IROTH) < 0)
			&& (errno != EEXIST)) {
		perror("mkfifo:");
	}
	int fo = fork();
	if (fo > 0) {
		int fd = open(FIFO_FN, O_WRONLY);
		if (fd == -1) {
			perror("open pipe");
		}
		int flg = fcntl(fd, F_GETFL);
		if (flg < 0) {
			perror("fcntl:");
		}
		flg |= O_NONBLOCK;
		fcntl(fd, F_SETFL, flg);
		int wr;
		char buf[1024];
		printf("writing...\n");
		sleep(1);
		if ((wr = write(fd, buf, 1)) < 0) {//如果不 捕获或是忽略的话,程序遇到SIGPIPE 信号就直接退出,没有下面的了
			perror("write:");
			printf("errno:%d\n", errno);
		}
		printf("parent write over\n");
	}
	if (fo == 0) {
		int fd = open(FIFO_FN, O_RDONLY);
		printf("read open");
		close(fd);
		printf("closed\n");
		sleep(3);
		exit(0);
	}
	return 0;
}

运行结果:

[test@localhost coding]$ ./a.out 
writing...
read openclosed
signo:13
write:: Broken pipe
errno:32
parent write over

还有,运行分环境:centos 6.3  + GCC 

当然还有一些东西要做一些说明和解释,这个以后再细说吧.........




你可能感兴趣的:(FIFO读写产生SIGPIPE信号)