pipe_rw.c

来自「工ARM_LINUX的几个源代码」· C语言 代码 · 共 56 行

C
56
字号
/*pipe_rw.c*/
#include <unistd.h>
#include <sys/types.h>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
		int pipe_fd[2];
		pid_t pid;
		char buf_r[100];
		char *p_buf;
		int r_num;
		memset(buf_r,0,sizeof(buf_r));/*将一段内存内容全清为0。
/*创建管道*/
		if(pipe(pipe_fd)<0)
		{
		printf("pipe creat error\n");
		return -1;
		}
/*创建一子进程*/
		if((pid=fork())==0)
		{
				printf("\n");
/*关闭子进程写描述,并通过使父进程暂停2秒确保父进程已关闭相应的读描述符*/
		close(pipe_fd[1]);
		sleep(2);
/*子进程读取管道内容*/
		if((r_num = read(pipe_fd[0],buf_r,100))>0){
				printf("%d numbers read the pipe is %s\n",r_num,buf_r);
				}
/*关闭子进程读描述符*/
		close(pipe_fd[0]);
		exit(0);
		}
		else if(pid>0)
		{
/*/关闭父进程读描述符,并分两次向管道中写入Hello Pipe*/
		close(pipe_fd[0]);
		if(write(pipe_fd[1],"Hello ok",8)!=-1)
				printf("parent write1 success!\n");
		if(write(pipe_fd[1]," Pipe",5)!=-1)
				printf("parent write2 success!\n");
/*收集子进程退出信息*/
		waitpid(pid,NULL,0);
		exit(0);
		}
}
运行结果:
parent write1 success!
parent write2 success!

13 numbers read the pipe is Hello ok Pipe

⌨️ 快捷键说明

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