⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pipe4.c

📁 unix系统编程时
💻 C
字号:
#include <sys/types.h>		/* some systems still require this */#include <sys/stat.h>#include <sys/termios.h>	/* for winsize */#ifndef TIOCGWINSZ#include <sys/ioctl.h>#endif#include <stdio.h>		/* for convenience */#include <stdlib.h>		/* for convenience */#include <stddef.h>		/* for offsetof */#include <string.h>		/* for convenience */#include <unistd.h>		/* for convenience */#include <signal.h>		/* for SIG_ERR */#define	MAXLINE	1024			/* max line length */static void	sig_pipe(int);		/* our signal handler */intmain(void){	int		n, fd1[2], fd2[2];	pid_t	pid;	char	line[MAXLINE];	if (signal(SIGPIPE, sig_pipe) == SIG_ERR)		{printf("signal error\n"); exit(0);}	if (pipe(fd1) < 0 || pipe(fd2) < 0)		{printf("pipe error\n"); exit(0);}			if ((pid = fork()) < 0) {		printf("fork error\n"); exit(0);	} else if (pid > 0) {							/* parent */		printf("parent\n");		close(fd1[0]);		close(fd2[1]);		while (fgets(line, MAXLINE, stdin) != NULL) {			n = strlen(line);			if (write(fd1[1], line, n) != n)				{printf("write error to pipe\n"); exit(0);}			if ((n = read(fd2[0], line, MAXLINE)) < 0)				{printf("read error from pipe\n"); exit(0);}			if (n == 0) {				{printf("child closed pipe\n"); exit(0);}				break;			}			line[n] = 0;	/* null terminate */			if (fputs(line, stdout) == EOF)				{printf("fputs error\n"); exit(0);}		}		if (ferror(stdin))			{printf("fgets error on stdin\n"); exit(0);}		exit(0);	} else {									/* child */		printf("child\n");		close(fd1[1]);		close(fd2[0]);		if (fd1[0] != STDIN_FILENO) {			if (dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO)				{printf("dup2 error to stdin\n"); exit(0);}			close(fd1[0]);		}		if (fd2[1] != STDOUT_FILENO) {			if (dup2(fd2[1], STDOUT_FILENO) != STDOUT_FILENO)				{printf("dup2 error to stdout\n"); exit(0);}			close(fd2[1]);		}		if (execl("./add2", "add2", (char *)0) < 0)			{printf("execl error\n"); exit(0);}	}	exit(0);}static voidsig_pipe(int signo){	printf("SIGPIPE caught\n");	exit(1);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -