c中linux中进程间通信IPC之有名管道FIFO在实战中的应用??
有名管道的操作
有名管道在操作上和普通文件一样进行,如:open()、write()、read()、close() 等。但是,和无名管道一样,操作命名管道肯定要考虑默认情况下其阻塞特性。
1.以只读和只写方式 open 管道,并且没有指定非阻塞标志 O_NONBLOCK 。则:
open() 以只读方式打开 FIFO 时,要阻塞到另一个进程为写而打开此 FIFO;
open() 以只写方式打开 FIFO 时,要阻塞到另一个进程为读而打开此 FIFO。
通信过程中若写进程先退出了,就算命名管道里没有数据,调用 read() 函数从 FIFO 里读数据时不阻塞;若写进程又重新运行,则调用 read() 函数从 FIFO 里读数据时又恢复阻塞。
2.以只读和只写方式 open 管道,并指定非阻塞标志 O_NONBLOCK 。则 open() 函数不会阻塞。
非阻塞标志(O_NONBLOCK)打开的命名管道有以下特点:
先以只读方式打开,如果没有进程已经为写而打开一个 FIFO, 只读 open() 成功,并且 open() 不阻塞。
先以只写方式打开,如果没有进程已经为读而打开一个 FIFO,只写 open() 将出错返回 -1 。
read()、write() 读写命名管道中读数据时不阻塞。
3.以可读可写方式 open 管道,则 open() 函数不会阻塞。
特点:
read() 仍会阻塞,缓冲区满时,write() 也会阻塞;
通信过程中,读进程退出后,写进程向命名管道内写数据时,写进程不会退出。
通信过程中若写进程先退出了,如果名管道里没有数据,调用 read() 函数从 FIFO 里读数据时会阻塞,与第一种情况不同。
注:有名管道的名字存在于文件系统中,内容存放在内存中。
【案例】
//向有名管道中读写数据没有返回结果??在linux中用命令运行试试??
//向有名管道写数据进程
/* study.cpp 写端代码 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int ret;
ret = mkfifo("./FIFO", 0666);
if(ret != 0)
{
perror("mkfifo");
}
int fd_w;
printf("open之前\n");
/* 1. 以只写方式打开有名管道 */
fd_w = open("./FIFO",O_WRONLY);
/* 2. 以只写方式打开有名管道,非阻塞 */
//fd_w = open("./FIFO",O_WRONLY|O_NONBLOCK);
/* 3. 以可读可写方式打开有名管道 */
//fd_w = open("./FIFO",O_RDWR);
printf("open之后\n");
if(fd_w < 0)
{
perror("open");
_exit(-1);
}
char str[64];
int i = 0;
while (i<5)
{
i++;
memset(str,0,sizeof(str));
sprintf(str,"%d: hello world!",i);
printf("写:%s\n",str);
write(fd_w,str,strlen(str)+1);
sleep(2);
}
close(fd_w);
return 0;
}
//从有名管道中读数据进程
/* main.c 读端代码 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main()
{
int ret;
ret = mkfifo("./FIFO", 0666);
if(ret != 0)
{
perror("mkfifo");
}
int fd_r;
printf("open之前\n");
/* 1. 以只写方式打开有名管道 */
fd_r = open("./FIFO",O_RDONLY);
/* 2. 以只写方式打开有名管道,非阻塞 */
//fd_r = open("./FIFO",O_RDONLY|O_NONBLOCK);
/* 3. 以可读可写方式打开有名管道 */
//fd_r = open("./FIFO",O_RDWR);
printf("open之后\n");
if(fd_r < 0)
{
perror("open");
_exit(-1);
}
char str[64];
int i = 0;
while (i<10)
{
i++;
memset(str,0,sizeof(str));
read(fd_r,str,sizeof(str));
printf("读:%s\n",str);
sleep(1);
}
close(fd_r);
return 0;
}