2021-03-04

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
//int pipe(int pipefd[2]); //无名管道函数
//ssize_t write(int fd, const void *buf, size_t count);//写操作
//size_t read(int fd, void *buf, size_t count);//读操作
int main()
{
    int pipe_fd[2] = {0};//对管道进行 读写的fd定义;
    int status =0;
    char *buf = "this is from father!";
    char *readBuf;
    pipe(pipe_fd);//创建管道
    int pid;
    pid = fork();//创建进程,无名管道只能用于父子进程中,其他进程不得使用
    if(pid > 0)
    {    
        close(pipe_fd[0]); //fd[0]是读操作,在进行写操作的时候一定要关闭读操作。
        write(pipe_fd[1],buf,strlen(buf));
        printf("this is a father !\n");
        wait(&status);
        printf("%d\n",WEXITSTATUS(status)); // 宏定义 WEXITSTATUS 把从child中的exit() 解析出来。    
    }else if(pid ==0){
        readBuf = (char *)malloc(sizeof(char)*strlen(buf));
        close(pipe_fd[1]);
        read(pipe_fd[0],readBuf,strlen(buf));
        printf("read : %s\n",readBuf);
        printf("this is a child !\n");
        exit(0);
        
    }else{

        printf("fork error! \n");
    }
    return 0;
}


其中主要运用到几个API
1.创建管道 :int pipe(int pipefd[2]);
2.创建进程:pid = fork();
3.进行写操作:size_t read(int fd, void *buf, size_t count);
4.进行读操作:ssize_t write(int fd, const void *buf, size_t count)
5.在father进程的中进行wait(*),然后再使用WEXITSTATUS(status),解析出child中的exit返回的值。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值