前言
如果,想要深入的学习C标准库函数中的mkfifo函数,还是需要去自己阅读Linux系统中的帮助文档。
-
具体输入命令:
man 3 mkfifo
-
即可查阅到完整的资料信息。
mkfifo函数
mkfifo 是标准 C 库中的一个函数,
用于在文件系统中创建一个有名管道(命名管道)。
有名管道允许两个或多个进程之间进行通信,即使它们并不具有父子关系。在 Linux 系统中,有名管道以特殊的文件形式存在,可以使用常规的文件 I/O 函数(如 open、read、write 等)对其进行操作。
mkfifo 函数原型如下:
//需导入的头文件
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
参数说明:
- pathname:指向一个字符串,表示要创建的有名管道文件的路径。
- mode:指定有名管道的权限。它是一个位掩码,可用来指定文件的读、写、执行权限。通常,可以使用 S_IRUSR、S_IWUSR、S_IRGRP、S_IWGRP、S_IROTH 和 S_IWOTH 等宏来设置不同的权限组合。
返回值:
- 如果成功创建有名管道,函数返回 0。
- 如果创建有名管道失败,函数返回 -1,并设置 errno 为相应的错误代码。
示例:
以下是一个简单的示例,演示了如何使用 mkfifo 函数创建一个有名管道:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
int main() {
const char *pathname = "/tmp/my_fifo";
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
if (mkfifo(pathname, mode) == 0) {
printf("Named pipe created successfully.\n");
} else {
perror("Error creating named pipe");
}
return 0;
}
在这个示例中,我们创建了一个名为 /tmp/my_fifo 的有名管道,权限设置为用户、组和其他都可读写。如果成功创建有名管道,程序会输出相应的消息,否则会输出错误信息。
需要注意的是,创建有名管道后,需要使用 open、read、write 等函数对其进行操作。通常,一个进程以只读方式打开管道,另一个进程以只写方式打开管道,从而实现进程间通信。当不再需要有名管道时,可以使用 unlink 函数删除它。
示例:模拟一个进程以只读方式打开管道,另一个进程以只写方式打开管道,实现进程间通信
读端代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int ret = access("fifo1", F_OK);
if (ret == -1)
{
printf("管道不存在创建管道\n");
ret = mkfifo("fifo1", 0664);
if (ret == -1)
perror("mkfifo");
}
int fd = open("fifo1", O_RDONLY);
if (fd == -1)
{
perror("open");
}
char buf[1024] = {0};
while (1)
{
int len = read(fd, buf, sizeof(buf));
if (len == 0)
{
printf("写端已关闭") break;
}
else if (len == -1)
{
perror("read");
close(fd);
exit(0);
}
printf("收到来自写端写入的数据:%s\n", buf);
memset(buf, 0, 1024);
}
close(fd);
return 0;
}
写端代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main (){
int ret = access("fifo1",F_OK);
if(ret == -1){
printf("管道不存在创建管道\n");
ret = mkfifo("fifo1",0664);
if(ret == -1) perror("mkfifo");
}
int fd = open("fifo1",O_WRONLY);
if(fd == -1){
perror("open");
}
char buf [1024] = {0};
for(int i = 0; i < 20; ++i){
sprintf(buf,"hello,这里是写端,正在写入数据:%d\n",i);
write(fd,buf,sizeof(buf));
sleep(1);
memset(buf,0,1024);
}
close(fd);
return 0;
}