Linux管道

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
/*

3.编写程序实现以下功能:
利用有名管道文件实现进程间通信,要求
写进程向有名管道文件写入10次“hello world”;
读进程读取有名管道文件中的内容,并依次打印。
*/
int main() {
    int pid ,fd;
/*
基本函数
int mkfifo(const char * pathname, mode_t mode);
参数说明
pathname:创建的FIFO名字
mode:规定FIFO的读写权限
返回值
成功时返回0
失败时返回-1
若路径名存在,则返回EEXIST错误
说明
一般文件的I/O函数都可用于管道,如open(), close(), read(), write()等。
————————————————
*/
    if(mkfifo("fifotest" ,0666)< 0)
        perror(" mnkfifo" );
    pid = fork();
    if(pid < 0)
        perror("fork");
    else if(pid == 0) {
        printf("This is the write process! \n");
        int fd = open("fifotest",0666);
        for(int i = 0; i < 10; i++) {
            if(write(fd ,"hello world",12)<0)
                perror( "write" );
            sleep(1);
        }
        close(fd);
    } else {
        char str[128];
        printf( "This is the read process!\n ");
        int fd1 = open( "fifotest" ,0666);
        for(int i = 0; i < 10; i++)
            {
            
                if(read(fd1,str,128)<0)
                    perror( "read" );
                else
                    printf( "%s\n" ,str);
            }
            system( "rm -f fifotest");
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值