- 创建FIFO:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
const char* fifo_name = "my_fifo";
// 创建命名管道
if (mkfifo(fifo_name, 0666) == -1) {
perror("mkfifo");
return 1;
}
return 0;
}
mkfifo
函数:
- 函数原型:
int mkfifo(const char *pathname, mode_t mode);
- 作用:创建一个命名管道(FIFO),
pathname
是要创建的FIFO的路径名,mode
指定了FIFO的权限,如0666
表示所有者、组和其他用户都有读和写的权限。如果创建成功返回0,否则返回 -1,并设置errno
来指示错误原因。
- 打开FIFO进行读写操作(以读操作进程为例):
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
const char* fifo_name = "my_fifo";
int fd;
char buffer[1024];
// 打开FIFO进行读操作
fd = open(fifo_name, O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
// 从FIFO读取数据
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read == -1) {
perror("read");
close(fd);
return 1;
}
buffer[bytes_read] = '\0';
printf("Read from FIFO: %s\n", buffer);
close(fd);
return 0;
}
open
函数:
- 函数原型:
int open(const char *pathname, int flags);
- 作用:打开一个文件或设备,在这里用于打开命名管道。
pathname
是FIFO的路径名,O_RDONLY
表示以只读方式打开。如果打开成功返回文件描述符,否则返回 -1,并设置errno
指示错误原因。
read
函数:
- 函数原型:
ssize_t read(int fd, void *buf, size_t count);
- 作用:从文件描述符
fd
对应的文件中读取数据到buf
缓冲区,count
指定最多读取的字节数。返回实际读取的字节数,如果出错返回 -1,并设置errno
。
- 打开FIFO进行读写操作(以写操作进程为例):
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
const char* fifo_name = "my_fifo";
int fd;
const char* message = "Hello, FIFO!";
// 打开FIFO进行写操作
fd = open(fifo_name, O_WRONLY);
if (fd == -1) {
perror("open");
return 1;
}
// 向FIFO写入数据
ssize_t bytes_written = write(fd, message, strlen(message));
if (bytes_written == -1) {
perror("write");
close(fd);
return 1;
}
close(fd);
return 0;
}
write
函数:
- 函数原型:
ssize_t write(int fd, const void *buf, size_t count);
- 作用:向文件描述符
fd
对应的文件中写入数据,buf
是要写入的数据缓冲区,count
指定要写入的字节数。返回实际写入的字节数,如果出错返回 -1,并设置errno
。