您的位置:首页 > 运维架构 > Linux

Linux 进程通信学习1-管道

2016-11-07 21:57 183 查看
*进程通信的目的:1、进程间数据传输2、进程之间资源共享3、进程通知事件,发送消息4、进程的控制,一个进程完全控制另一个进程如debug进程。*名词解释:IPC(interprocess comunication) 进程间通信POSIX 可移植的操作系统接口*Linux进程间通信的7种主要方式:无名管道pipe、有名管道FIFO,信号signal、消息队列、共享内存、、信号量、套接字socket*管道通信  一个进程在尾部写入数据另一个进程从管道头部读出数据。  无名管道:只能用于父进程和子进程间的通信。  有名管道: 运行于同一系统的任意两个进程间的通信。  特点:    管道通信是单向的,有固定的读端口和写端。    数据被进程读出后,管道中的数据就不存在了    进程读取空管道的时候,进程会阻塞。    当进程像满管道写入数据的时,进程会阻塞。    管道的容量为64KB(../include/linux/pipe_fs_i.h)    #define  ..buffer   16  //16*4kb >无名管道:    无名管道被创建后等同于操作文件,读端被视为一个文件,在写端也被视为一个文件。   无名管道:只能用于父进程和子进程间的通信。   创建无名管道:       int pipe(int pipefd[2]);  // 成功返回0,失败返回-1       pipefd[0],返回2个文件描述符中的读端,pipefd[1],返回2个文件描述符中的写端,          *注意需要在fork之前创建管道。      关闭管道:close      读管道:read      写管道:write      程序例子:  
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <stdlib.h>
void main()
{
pid_t pid;
int pipefd[2];
char buf[10];
pipe(pipefd);//先创建一个管道
pid=fork();//创建一个进程
if(pid>0) //父进程
{
write(pipefd[1],"hello",6);//写管道
wait();//wait for read
close(pipefd[1]);//关闭
exit(0);
}
if(pid==0) //子进程
{
read(pipefd[0],buf,6);
printf("%s\n",buf);
close(pipefd[0]);
exit(0);
}
}
      >有名管道    FIFO|pipe区别:     读取fifo文件的进程只能一只读的方式打开。     写fifo文件的进程只能以只写的方式打开。     数据被进程读出后,管道中的数据就不存在。    创建有名管道:         int mkfifo(const char * pathname,mode_t mode);//创建一个fifo 文件(有名管道)         pathname:要创建文件的名字-含路径         mode:创建文件的权限    删除有名管道         int unlink(const char * pathname);    打开open 写 write 读read 关闭 close     
//write.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <stdlib.h>
void main()
{
int fd;
mkfifo("/tmp/myfifo",0666);//先创建一个管道
fd=open("/tmp/myfifo",WRONLY);//先创建一个管道</span>
write(fd,"hello",6);//写管道,当写入的时候没有读进程会进入阻塞
close(fd);//关闭
}
//read.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <stdlib.h>
void main()
{
int fd;
char buf[15];
fd=open("/tmp/myfifo",WRONLY);//先创建一个管道</span>
read(fd,buf,6);//写管道
printf("%s\n",buf);
close(fd);//关闭
unlink("/tmp/myfifo");//删除管道</span>
}
       
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: