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

📄 pipe.c

📁 操作系统编程
💻 C
字号:
#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <errno.h>int main(int argc, char *argv[]){	int pfd[2];	int rtn, rtn_1, flag;	pid_t pid, pid_1;	long v;	ssize_t nread;	char buf[256];	memset(buf, 0, sizeof(buf));	if(pipe(pfd) == -1){		printf("pipe() error\n");		exit(1);	}	v = fpathconf(pfd[0], _PC_PIPE_BUF);	if(v == -1){		printf("no limit for PIPE_BUF");	}else{		printf("\nPIPE_BUF = %ld\n", v);	}	if((pid = fork()) == -1){		printf("fork() error\n");		exit(1);	}	else if(pid == 0){		/* child process */		close(pfd[0]);		write(pfd[1], "child 1 hello!", sizeof("child 1 hello!"));		//printf("child 1 process write \"child 1 hello!\" to the pipe\n");		//sleep(10);		//close(pfd[1]);		exit(0);	}	else if(pid > 0){		/* parent process */		pid_1 = fork();		if(pid_1 == -1){			printf("fork() 2 error\n");			exit(1);		}		if(pid_1 == 0){			/*second child process*/			/* printf("\nchild 2 returned pid 1: %d\n", rtn = waitpid(pid, NULL, 0)); */			/* printf("\nerror code: %d, info: %s\n", errno, strerror(errno)); */							close(pfd[0]);			sleep(0);			rtn = write(pfd[1], "child 2 world!", sizeof("child 2 world!"));			if(rtn == -1){				printf("write 2 error\n");			}			//close(pfd[1]);			//printf("\nchild 2 process write \"child 2 world!\" to the pipe\n");			exit(0);					}		//close(pfd[1]); /*block model*/		while(1){			/* printf("\nparent returned pid 1: %d\n", rtn = waitpid(pid, NULL, 0)); */			/* printf("\nerror code: %d, info: %s\n", errno, strerror(errno)); */			nread = read(pfd[0], buf, sizeof(buf));						if(nread == -1){				printf("read() error\n");				exit(1);			}			if(nread == 0){				/*No Use when Block Model*/				printf("\nNothin in Pipe\n");				break;			}else{				printf("\nparent read from the pipe: \"%s\"\n", buf);			}			/* printf("\nparent returned pid 2: %d\n", rtn_1 = waitpid(pid_1, NULL, 0)); */			/* printf("\nerror code: %d, info: %s\n", errno, strerror(errno)); */			rtn_1 = waitpid(pid_1, NULL, 0);			if(rtn_1 == -1){				printf("\nAll Done\n");				break;			}		}		}	exit(0);}

⌨️ 快捷键说明

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