有名管道——利用有名管道实现单向进程聊天

文章展示了如何通过C语言使用mkfifo函数创建有名管道,并利用文件IO的读写函数实现两个进程间的通信。程序包括一个写入数据的进程和一个读取打印数据的进程,通过有名管道进行数据传输。
摘要由CSDN通过智能技术生成

有名管道

用于任意进程间的通信,涉及到特殊文件(p)

#include<sys/types.h>

#include<sys/stat.h>

int mkfifo(const char *pathname,mode_t mode);——创建有名管道

参数:

pathname:有名管道的名字(带路径)

mode:创建有名管道的权限

返回值:

成功返回0,失败返回-1,并返回错误码

注意:管道文件是由内核区域映射映射上来的,故其大小永远为0;

思路

首先通过mkfifo来创建管道文件并确定权限,通过文件IO的相关读写函数实现两个文件的读写操作。

相关代码

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

int main(int argc,char *argv[]){
    if(argc!=2){
        printf("User:%s<fifoname>\n",argv[0]);
        exit(-1);
    }
    
    if(access(argv[1],F_OK)){       //通过access函数来判断是否存在了管道文件
        if(mkfifo(argv[1],0666)){   // 创建管道文件
            perror("mkfifo");
            exit(-1);
        }
    }
    
    int fd=open(argv[1],O_RDWR);
    if(fd<0){
        perror("open");
        exit(-1);
    }
    char buf[40];
    while(1){
        bzero(buf,sizeof(buf));
        scanf("%s",buf);
        write(fd,buf,strlen(buf));  // 写入操作
    }
    
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main(int argc,char *argv[]){
    if(argc!=2){
        printf("User:%s<fifoname>\n",argv[0]);
        exit(-1);
    }
    
    if(access(argv[1],F_OK)){
        if(mkfifo(argv[1],0666)){
            perror("mkfifo");
            exit(-1);
        }
    }
    
    int fd=open(argv[1],O_RDWR);
    if(fd<0){
        perror("open");
        exit(-1);
    }
    char buf[40];
    while(1){
        bzero(buf,sizeof(buf));
        read(fd,buf,sizeof(buf));   // 读取操作,并打印
        printf("%s\n",buf);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值