使用mkfifo命令或者函数创建命名管道。
1.使用mkfifo命令
[root@iz2zefozq9h39txdb8s7npz shelldemo]# mkfifo myfifo
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ls -l myfifo
prw-r--r-- 1 root root 0 Dec 6 20:55 myfifo
以p开头说明是管道文件。
2.使用mkfifo函数 函数原型:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo( const char *pathname, mode_t mode);
参数: - pathname: 普通的路径名,也就是创建后 FIFO 的名字。 - mode: 文件的权限,与打开普通文件的 open() 函数中的 mode 参数相同。
返回值: - 成功:0 - 失败:如果文件已经存在,则会出错且返回 -1。
实例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/errno.h>
int main(int argc, char *argv[])
{
int ret;
ret = mkfifo("my_fifo", 0664); // 创建命名管道
if (ret != 0)
{ // 出错
if (errno != 17)
{
perror("erro to mkfifo:");
//printf("errerno=%d\n",errno); //如果管道已经创建则errno值为17.
exit(1);
}
}
printf("hello,world!\n");
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
hello,world!