创建
方式一
shell 命令创建
mkfifo -m 777 myfifo
方式二
#include <sys/types.h>
#include <sys/stat.h>
/**
* [mkfifo 创建有名管道]
* @param pathname [需要创建的管道文件名称(绝对路径和相对路径)]
* @param mode [设置管道文件的访问权限(mode & ~umask)]
* @return [成功返回0,失败返回-1且修改errno的值]
*/
int mkfifo(const char *pathname, mode_t mode);
实例
发送
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd;
int ret;
char buf[256];
/*1. 打开有名管道文件 */
fd = open("myfifo", O_WRONLY);
if (fd == -1)
{
perror("open");
return -1;
}
while(1)
{
/* 键盘获取数据 */
fgets(buf, sizeof(buf), stdin);
/* 写数据到有名管道文件中:发送数据 */
ret = write(fd, buf, sizeof(buf));
if (ret == -1)
{
perror("write");
return -1;
}
}
close(fd);
}
接收
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd;
int ret;
char buf[256];
/*1. 打开有名管道文件 */
fd = open("myfifo", O_RDONLY);
if (fd == -1)
{
perror("open");
return -1;
}
while(1)
{
/* 清空buf中数据 */
memset(buf, 0, sizeof(buf));
/* 从有名管道文件中读数据:接收数据 */
ret = read(fd, buf, sizeof(buf));
if (ret == -1)
{
perror("read");
return -1;
}
else if(ret == 0)
{
break;
}
printf("buf : %s\n", buf);
}
close(fd);
}
网友评论