linux c语言 管道

一、有名管道
特点:

1、创建之后会在文件系统以管道文件的形式存在

2、可以在任意两个进程间通信,没有固定的读写端

代码:

#include <stdio.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <stdlib.h>

#include <unistd.h>

int main(int argc, char *argv[])

{

// 创建管道,在文件系统生成fifo管道文件

int ret=mkfifo("fifo",0664);//0664赋文件权限

//0664--> rw- rw- -w-,每一位依次对应<用户>、<用户组><其他>的权限,每个权限又对应读(r)写(w)执行(x)

if(ret<0)

{

printf("mkfifo fail\r\n");//ret<0,就输出创建错误原因

return(-1);

}

/* 写入fifo */

#if 1

int fd=open("fifo",O_WRONLY);//以‘仅写’打开管道

if(fd<0)

{

printf("open fifo fail\r\n");

return(-1);

}

char send_buf[256]={0};//定义缓冲区大小

while(1)

{

fgets(send_buf,sizeof(send_buf),stdin);//获取输入的字符串

write(fd,send_buf,strlen(send_buf));//写入

}

close(fd);

#endif

/* 读取fifo */

#if 0

int fd=open("fifo",O_RDONLY);//以‘仅读’打开管道

if(fd<0)

{

printf("open fifo");

return(-1);

}

char recv_buf[64]={0};

while(1)

{

read(fd,recv_buf,sizeof(recv_buf));//读取缓冲区

printf("recv msg:%s\r\n", recv_buf);//输出

}

close(fd);

#endif

return 0;

}

二、无名管道

特点:

1、创建之后在文件系统不可见

2、半双工通信

3、固定的读端(0),写端(1)

4、只能用于具有亲缘关系的进程间的通信

代码:

#include <stdio.h>

#include <unistd.h>

#include <string.h>

int main(int argc, const char *argv[])

{

int pipe_fd[2]; // pipe_fd[0] 为读端 pipe_fd[1] 为写端

int ret = pipe(pipe_fd);

if(ret < 0)

{

printf("fail to pipe\n");

return -1;

}

pid_t pid = fork();

if(pid > 0)

{

close(pipe_fd[0]); // 关闭读端

while(1)

{

char buff[1024] = "send msg: hello world\r\n";

write(pipe_fd[1], buff, strlen(buff)+1);

}

wait(NULL);

close(pipe_fd[1]);

}

else if(0 == pid)

{

close(pipe_fd[1]); // 关闭写端

while(1)

{

char buff[1024] = {0};

read(pipe_fd[0], buff, sizeof(buff));

printf("recv msg:%s", buff);

}

close(pipe_fd[0]);

}

else

{

printf("fail to fork\n");

return -1;

}

return 0;

}

有名和无名之间区别:

1、无名只能在有亲缘关系的进程通信

2、有名也称命名管道,可以在任意两个进程间通信

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值