C语言实现简单的管道通信(测试成功)

本文通过两个C语言程序(server.c和client.c)演示了如何实现简单的管道通信。利用管道作为进程间通信的方式,实现了数据的传递。通过makefile编译并运行这些程序,测试成功。

server.c

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
    umask(0); //允许进程创建文件时有最大权限
    if(mkfifo("mypipe",0644)<0)    //创建命名管道
    {
        perror("mkfifo");            //创建失败
        exit(1);
    }
    int rfd=open("mypipe",O_RDONLY);     //只读方式打开管道
    if(rfd<0)
    {
        perror("open");                //打开失败
        exit(1);
    }

    char buf[1024];                 //缓冲区
    while(1)
    {
        buf[0]=0;
        printf("please wait....\n");   
        ssize_t s=read(rfd,buf,sizeof(buf)-1);  //读取rfd内容到buf
        if(s>0)
        {
            buf[s-1]=0;                  //读取成功
            printf("client say # %s\n",buf);

        }
        else if(s==0)                    //读到文件结尾,或无可读数据
        {
            printf("server quit");
            exit(0);
        }
        else               //读取失败
        {
            perror("read");
            exit(1);
        }
    }
    close(rfd);    //关闭读取
    return 0 ;
}


client.c

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

int main()
{

		int wfd=open("mypipe",O_WRONLY);  //只写方式打开管道
		if(wfd<0)                        
		{
				perror("open");     //打开失败
				exit(1);
		}
		char buf[1024];      //缓冲区
		while(1)
		{
				buf[0]=0;             
				printf("please enter#");
				fflush(stdout);   //刷新
				ssize_t s=read(0,buf,sizeof(buf)-1);  //从当前读入buf中
				if(s>0)
				{              //读取成功
						buf[s]=0;
						write(wfd,buf,sizeof(buf)-1);  //从buf中往wfd所在文件中写
				}
				else if(s<=0)     
				{
						perror("read");    //读取失败
						exit(1);
				}
		}
		close(wfd);   //关闭写入
		return 0 ;
}

makefile

.PHONY :all
all:client server
client:client.c
	gcc -o $@ $^
server:server.c
	gcc -o $@ $^ 

.PHONE :clean
clean :
	rm -f client server
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值