进程通信之管道通信
来源:互联网 发布:如何评价北京人 知乎 编辑:程序博客网 时间:2024/05/16 03:35
管道通信有一个特点:通信是半双工的,即管道的一端只能读或者只能写
管道通信可以分为:匿名管道通信和命名管道通信两种
1. 匿名管道通信:适合用于父子进程间的通信
#include<unistd.h>
#include<stdio.h>
#include<string.h>
/*
匿名管道通信,本机父子进程通信方式
*/
int main()
{
int pipefd[2];
pid_t pid;
char buf[20];
pipe(pipefd); //create pipe!
pid = fork();
if(pid < 0)
printf("fork failed\n");
if(pid > 0)
{
close(pipefd[0]);
const char* s = "hello child";
printf("i am father , i am writting :%s\n",s);
write(pipefd[1],s,strlen(s)+1);
close(pipefd[1]);
}
else
{
close(pipefd[1]);
read(pipefd[0],buf,sizeof(buf));
printf("i am child,i am reading :%s\n",buf);
close(pipefd[0]);
}
waitpid(pid,NULL,0);
return 0;
}
2. 命名管道通信:用于任何两个进程间的通信
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
/**
命名管道
*/
#define FIFO "/home/wyz19891024/code/ccode/fifo"
int main()
{
int ret;
int fd;
//const char* s = "hello bothers!";
char buf[20];
umask(0); //默认文件访问权限022 umask(mode)
ret = mkfifo(FIFO,0666); //文件权限为 0666 & (~0);
if(ret < 0)
{
printf("mkfifo failed\n");
return 1;
}
fd = open(FIFO,O_WRONLY);
while(1)
{
fgets(buf,sizeof(buf),stdin);
write(fd,buf,sizeof(buf));
if(strncmp(buf,"quit",4) == 0)
{
unlink(FIFO);
close(fd);
break;
}
}
return 0;
}
/****-----client------****/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
/**
命名管道
*/
#define FIFO "/home/wyz19891024/code/ccode/fifo"
int main()
{
int fd;
char buf[20];
fd = open(FIFO,O_RDONLY);
while(1)
{
read(fd,buf,sizeof(buf));
printf("get %s\n",buf);
if(strncmp(buf,"quit",4) == 0)
break;
}
close(fd);
return 0;
}
- 进程通信之管道通信
- 进程通信之管道通信
- 进程通信之管道通信
- 【进程通信】之管道通信
- 进程通信之管道
- 进程通信之管道
- 进程通信之管道
- 进程通信之管道
- 进程通信之管道
- [进程通信] 进程间通信 之 管道
- 进程间通信之管道通信
- 进程通信之管道通信pipe
- Linux进程间通信之管道通信
- Linux进程间通信之管道通信
- Linux进程通信之管道通信
- 进程间通信之匿名管道通信
- 进程间通信之管道通信
- 进程通信之管道(续)
- Win7上VirtualBox的虚拟机与宿主机以及虚拟机间的通信
- 开源静态分析工具androguard体验(二)
- 撼枚乘盗燎占贺谕雍窒段刺感彩永览
- 达姆弹,据说是比生化武器还要恐怖的子弹?
- 武安驾校报名送话费活动公告
- 进程通信之管道通信
- 瞥杉纸仓匙古侣酝霞位氛蔚钢盗局略
- AIX 日常维护命令
- 用C#做的简单工厂模式
- 命名管道实现进程间通信--石头、剪刀、布游戏
- 仔瞥杉纸仓匙古侣酝霞位氛蔚
- 大家好
- cocos2d-x 3.0 使用UILayout布局开发
- Setting up an SSL secured Webserver with CentOS