linux匿名管道特性探究
1.匿名管道是IPC方式之一。它最大的优点就是使用简单。本质上是一个伪文件。
总结,匿名管代具有以下特性:
- 伪文件
- 管道中的数据智能读取一次。
- 数据在管道中智能单向流动。
局限性:
- 自己写不能自己读。
- 数据不能反复读。
- 半双工通信
- 只有有血缘关系之间的进程才能使用。
读写特性:
读管道:
1. 管道有数据,read返回实际读到的字节数。
2. 管道无数据: 1)无写端,read返回0 (类似读到文件尾)
2)有写端,read阻塞等待。
写管道:
1. 无读端, 异常终止。 (SIGPIPE导致的)
2. 有读端: 1) 管道已满, 阻塞等待
2) 管道未满, 返回写出的字节个数。
下面是一个测试管道的特性测试。
#include <head.h>
#define MAX_PROCESS (1)
int main(int argc, char *argv[])
{
int pipefd[2];
int i=0;
// if (argc != 2)
// {
// fprintf(stderr, "Usage: %s <string>\n", argv[0]);
// exit(EXIT_FAILURE);
// }
if (pipe(pipefd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
for(;i<MAX_PROCESS;i++){
pid_t p =fork();
if (p == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if(p == 0){
break;
}
}
if (i == MAX_PROCESS)
{
close(pipefd[0]); /* Close unused read end */
char buf[1024];
for (size_t k = 0; k <4; k++)
{
CLEAR_ARRAY(buf);
time_t t =time(NULL);
strcpy(buf,ctime(&t));
write(pipefd[1],buf,strlen(buf));
sleep(1);
}
close(pipefd[1]); /* Reader will see EOF */
for(i=0;i<MAX_PROCESS;i++){
wait(NULL);
}
exit(EXIT_SUCCESS);
}
else
{
close(pipefd[1]); /* Close unused write end */
char buf[1024];
for (size_t k = 0; k < 10; k++)
{
CLEAR_ARRAY(buf);
// printf("child before read\n");
int len = read(pipefd[0],buf,sizeof(buf)-1);
// printf("child after read\n");
printf("[%d]read [%d]bytes:%s",i,len,buf);
sleep(1);
printf("sleep\n");
}
close(pipefd[0]);
_exit(EXIT_SUCCESS);
}
}