匿名管道,只能用于具有亲缘关系的进程见进行通信。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(){
int n=100;
int fd[2];
pid_t pid;
char line[1024]="";
if(pipe(fd)<0){
printf("error\n");
return -1;
}
if((pid=fork())<0){
printf("fork error\n");
return -1;
}else if(pid==0){
write(fd[1],"hello1",7);
n=read(fd[0],line,1024);
printf("child process, get %s pid=%d\n",line,getpid());
sleep(2);
write(fd[1],"hello2",7);
}else{
sleep(1);
close(fd[1]);
n=read(fd[0],line,1024);
printf("father process, get %s pid=%d\n",line,getpid());
}
return 0;
}
命名管道。
以下文字摘抄至Linux进程间通信——使用命名管道
关于打开FIFO的注意事项
与打开其他文件一样,FIFO文件也可以使用open调用来打开。注意,mkfifo函数只是创建一个FIFO文件,要使用命名管道还是将其打开。
但是有两点要
注意,1、就是程序不能以O_RDWR模式打开FIFO文件进行读写操作,而其行为也未明确定义,因为如一个管道以读/写方式打开,进程就会读回自己的输出,同时我们通常使用FIFO只是为了单向的数据传递。2、就是传递给open调用的是FIFO的路径名,而不是正常的文件。
打开FIFO文件通常有四种方式,
open(const char *path, O_RDONLY);//1
open(const char *path, O_RDONLY | O_NONBLOCK);//2
open(const char *path, O_WRONLY);//3
open(const char *path, O_WRONLY | O_NONBLOCK);//4
在open函数的调用的第二个参数中,你看到一个陌生的选项O_NONBLOCK,选项O_NONBLOCK表示非阻塞,加上这个选项后,表示open调用是非阻塞的,如果没有这个选项,则表示open调用是阻塞的。
open调用的阻塞是什么一回事呢?很简单,对于以只读方式(O_RDONLY)打开的FIFO文件,如果open调用是阻塞的(即第二个参数为O_RDONLY),除非有一个进程以写方式打开同一个FIFO,否则它不会返回;如果open调用是非阻塞的的(即第二个参数为O_RDONLY | O_NONBLOCK),则即使没有其他进程以写方式打开同一个FIFO文件,open调用将成功并立即返回。
对于以只写方式(O_WRONLY)打开的FIFO文件,如果open调用是阻塞的(即第二个参数为O_WRONLY),open调用将被阻塞,直到有一个进程以只读方式打开同一个FIFO文件为止;如果open调用是非阻塞的(即第二个参数为O_WRONLY | O_NONBLOCK),open总会立即返回,但如果没有其他进程以只读方式打开同一个FIFO文件,open调用将返回-1,并且FIFO也不会被打开。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#define WRITE_FIFO 1//写进程,实际运行时只选择一个开启
#define READ_FIFO 1//读进程
int main(){
const char* name="my_test_fifo";
#ifdef WRITE_FIFO
unlink(name);
if(mkfifo(name,0666)==-1){
printf("mkfifo error\n");
return -1;
}
char line[1024]="";
int fd=open(name,O_WRONLY);
if(fd==-1){
printf("open write error\n");
return -1;
}
int cnt=0;
while(cnt!=10){//往里面写数据
char data[100]="ha";
data[2]=cnt%10+'0';
if(write(fd,data,strlen(data)+1)<=0)
printf("write fail\n");
printf("write success %s ,length=%d\n",data,strlen(data));
++cnt;
sleep(1);
}
printf("Write complete\n");
close(fd);
#endif
#ifdef READ_FIFO
char line1[1024]="";
int fd1=open(name,O_RDONLY);
if(fd1==-1){
printf("open read error\n");
return -1;
}
while(true){
read(fd1,line1,1024);
printf("get %s\n",line1);
if(strcmp(line1,"ha9")==0)
break;
}
printf("Read Complete\n");
close(fd1);
#endif
return 0;
}