进程间通信之管道

管道是Linux中很重要的一种通信方式,调用pipe()函数时,会在内核中开辟一块缓冲区即管道。该缓冲区的大小固定,为1页即4kb

管道:不同的进程来访问同一资源

生命周期:随进程。

管道分为匿名管道命名管道

匿名管道:

 
 
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pipefd[ 2] = { 0, 0};
if((pipe(pipefd))< 0)
{
perror( "pipe");
return 1;
}
pid_t id = fork();
if(id < 0)
{
perror( "fork");
return 2;
}
else if(id == 0)
{
//child--write
close(pipefd[ 0]);
const char* msg = "hello bit";
int count = 5;
while(count)
{
write(pipefd[ 1],msg, strlen(msg));
count--;
sleep( 1);
}
close(pipefd[ 1]);
exit( 0);
}
else
{
//father--read
close(pipefd[ 1]);
char buf[ 128];
int count= 5;
while(count)
{
ssize_t _s=read(pipefd[ 0],buf, sizeof(buf)- 1);
if(_s> 0)
{
buf[_s]= '\0';
printf( "child->father:%s\n",buf);
}
else
{
close(pipefd[ 0]);
return 3;
}
count--;
}
close(pipefd[ 0]);
}
return 0;
}

注:匿名管道只能用于具有血缘关系的进程之间(多是父子进程)。

命名管道:

 
 
server.c:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
int main()
{
umask( 0);
if(mkfifo( "./fifo", 0666|S_IFIFO)< 0)
{
perror( "mkfifo");
return 1;
}
int fd=open( "./fifo",O_RDONLY);
if(fd< 0)
{
perror( "open");
return 2;
}
char buf[ 128];
while( 1){
ssize_t s=read(fd,buf, sizeof(buf));
if(s> 0)
{
buf[s]= '\0';
printf( "client: %s\n",buf);
}
else if(s== 0)
{
printf( "client is quit,sever also should quit\n");
break;
}
else{
perror( "read");
return 3;
}
}
close(fd);
return 0;
}
client.c:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
int main()
{
int fd=open( "./fifo",O_WRONLY);
if(fd< 0)
{
perror( "open");
return 2;
}
char buf[ 128];
while( 1){
printf( "please enter: ");
fflush( stdout);
ssize_t s=read( 0,buf, sizeof(buf));
if(s> 0)
{
buf[s- 1]= '\0';
write(fd,buf, strlen(buf));
}
}
close(fd);
return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值