服务器端代码逻辑
- 创建命名管道:使用
mkfifo
函数创建命名管道,函数原型为 int mkfifo(const char *pathname, mode_t mode);
,pathname
是命名管道的路径名,mode
是管道的权限。
- 打开命名管道:使用
open
函数以读模式打开命名管道,int open(const char *pathname, int flags);
,pathname
是管道路径,flags
设为 O_RDONLY
。
- 读取消息:使用
read
函数从管道读取数据,ssize_t read(int fd, void *buf, size_t count);
,fd
是管道文件描述符,buf
是存储读取数据的缓冲区,count
是最多读取的字节数。
- 打印消息:使用
printf
函数将读取到的消息打印出来。
- 关闭管道:使用
close
函数关闭管道,int close(int fd);
,fd
是管道文件描述符。
客户端代码逻辑
- 打开命名管道:使用
open
函数以写模式打开命名管道,flags
设为 O_WRONLY
。
- 写入消息:使用
write
函数向管道写入数据,ssize_t write(int fd, const void *buf, size_t count);
,fd
是管道文件描述符,buf
是要写入的缓冲区,count
是要写入的字节数。
- 关闭管道:使用
close
函数关闭管道。
示例代码
服务器端代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define FIFO_NAME "myfifo"
int main() {
int fd;
char buf[256];
// 创建命名管道
if (mkfifo(FIFO_NAME, 0666) == -1) {
perror("mkfifo");
exit(EXIT_FAILURE);
}
// 打开命名管道以读模式
fd = open(FIFO_NAME, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 从管道读取消息
if (read(fd, buf, sizeof(buf)) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", buf);
// 关闭管道
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
// 删除命名管道
if (unlink(FIFO_NAME) == -1) {
perror("unlink");
exit(EXIT_FAILURE);
}
return 0;
}
客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define FIFO_NAME "myfifo"
int main() {
int fd;
const char *msg = "Hello, server!";
// 打开命名管道以写模式
fd = open(FIFO_NAME, O_WRONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 向管道写入消息
if (write(fd, msg, strlen(msg) + 1) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
// 关闭管道
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
return 0;
}