1、管道(pipe)
用語具有親緣關系進程間的通信
匿名一次性使用的,半雙工。一個進程往輸出端寫管道,另一個進程從輸入端讀管道。
#include<unistd.h>
int pipe(int fd[2]);
fd[0]:表示讀端
fd[1]:表示寫端
2、有名管道(named pipe)
允許無親緣關系進程間的通信
有名管道,作為特別文件存儲于文件系統中。有名管道一旦建立就存在于文件系統中,除非顯示的unlink
#include<sys/tpes.h>
#include<sys/stat.h>
int mknod(const char *path,mode_t mod,dev_t dev);
int mkfifo(const char *path,mode_t mode);
path:創建有名管道的全路徑名
mod:創建有名管道的模式,指存取權限
dev:設備值,該值取決于文件創建的種類,它只在創建設備文件時才會用到
注意:有名管道創建后就可以使用了,有名管道和管道的使用方法基本是相同的。只是使用有名管道的時候必須先調用open()將其打開
因為有名管道是一個存在于硬盤上的文件,而管道是存在于內存中的特殊文件
下面的程序一個讀管道,另一個寫管道,這兩個函數用的是非阻塞讀寫管道
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO "/tmp/myfifo"
main(int argc, char** argv)
{
char buf_r[100];
int fd;
int nread;
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
printf("cannot create fifoserver\n");
printf("Preparing for reading bytes...\n");
memset(buf_r,0,sizeof(buf_r));
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==-1){
if(errno==EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
pause();
unlink(FIFO);
}
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO "/tmp/myfifo"
main(int argc,char** argv)
{
int fd;
char w_buf[100];
int nwrite;
if(fd==-1)
if(errno==ENXIO)
printf("open error; no reading process\n");
fd=open(FIFO,O_WRONLY|O_NONBLOCK,0);
if(argc==1)
printf("Please send something\n");
strcpy(w_buf,argv[1]);
if((nwrite=write(fd,w_buf,100))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try later\n");
}
else
printf("write %s to the FIFO\n",w_buf);
}
3、信號量
主要用于進程間及同一進程不同線程之間的同步手段
4、消息隊列
克服信號量有限,可寫可讀
5、信號(Signal)
比較復雜,用于通知接受進程有某事發生
6、共享內存
最有用的進程間通信方式,使得多個進程可訪問同以內存空間,但需要依靠某種同步機制
第一步:創建共享內存
第二步:映射共享內存
7、套接字
不同機器之間通信