一、管道通信的注意事项
(1)执行mkfifo file命令来创建一个管道文件。
[admin@localhost code]$ mkfifo pipe
[admin@localhost code]$ ls -l
total 0
'''p'rw-rw-r-- 1 admin admin 0 8月 30 19:52 pipe //p就代表是管道文件
(2)如果只把管道的写打开,管道是不通的,是写不进去的。
(3)只有把读、写都打开才能写进去。
二、代码示例(一个是写管道、一个读管道)
写管道:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
int nFd = 0;
int nWrLen = 0, nReadLen = 0;;
char szBuff[BUFSIZ] = {0};
/* 打开当前目录下的管道文件 */
nFd = open("pipe", O_RDWR);
if (-1 == nFd)
{
perror("Open fifo failed\n");
return 1;
}
while (1)
{
/* 从终端读取数据 */
memset(szBuff,0,BUFSIZ);
nReadLen = read(STDIN_FILENO,szBuff,BUFSIZ);
if(nReadLen > 0)
{
/* 往管道写入数据 */
nWrLen = write(nFd, szBuff, strlen(szBuff)+1);
if (nWrLen > 0)
{
printf("write data successful: %s \n", szBuff);
}
else
{
perror("write failed:");
}
}
}
}
读管道:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
int nFd = 0;
int nReadLen = 0;;
char szBuff[BUFSIZ] = {0};
/* 打开当前目录下的管道文件 */
nFd = open("pipe", O_RDWR);
if (-1 == nFd)
{
perror("Open fifo failed\n");
return 1;
}
while (1)
{
/* 从管道读取数据 */
memset(szBuff,0,BUFSIZ);
nReadLen = read(nFd,szBuff,BUFSIZ);
if(nReadLen > 0)
{
printf("read pipe data: %s\n", szBuff);
}
}
}