Linux管道操作

1 实验目的

理解Linux操作系统中管道的原理和使用方法。

学会编写简单的无名管道程序。

2 背景知识

#include<unistd.h>

int pipe(int filedes[2]);

返回值:成功,返回0,否则返回-1。参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道。

 

3实验内容

首先调用pipe函数,产生一个无名管道。

使用fork函数,产生一个子进程。

子进程通过管道,发送数据给主进程。

主进程通过读取管道,获得子进程发送来的数据,并在屏幕上显示出来。

 

实现代码

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

int main() {
        int fd[2], len;
        char buf[200];
        pid_t cld_pid;
        if(pipe(fd) == -1) {
                puts("创建管道失败");
        }
        if((cld_pid = fork()) == 0) {        //zijincheng
                close(fd[1]);      //关闭写端口
                len = read(fd[0], buf, sizeof(buf));
                printf("1\n");
                buf[len] = '\0';
                printf("子进程从管道中读取的数据是:%s\n", buf);
                exit(0);
        } else {                                                        //fujincheng
                close(fd[0]);     //关闭读端口
                printf("2\n");
                sprintf(buf, "hellozzh,pid shi %d", cld_pid);
                write(fd[1], buf, strlen(buf));
                exit(0);
        }
        return 0;
}

 

posted @ 2020-05-21 12:00  Cool-baby  阅读(49)  评论(0)    收藏  举报