我试图在同一台机器上运行的两个不同程序之间实现IPC(在我的例子中是CentOS7)。为了实现一种松散耦合,我决定对 IPC 使用命名管道。因此,我正在使用以下示例并遇到了不同的问题。
创建并写入管道:
#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
using namespace std;
main() {
int fd;
char * myfifo = new char [12];
strcpy(myfifo, "./tmp/myfifo1");
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open("./tmp/myfifo1", O_WRONLY ); //open(myfifo, O_WRONLY | O_NONBLOCK);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
printf("File open\n");
write(fd, "entry [1]", sizeof("entry [1]"));
sleep(1);
write(fd, "entry [2]", sizeof("entry [2]"));
sleep(2);
write(fd, "entry [3]", sizeof("entry [3]"));
printf("Content written\n");
close(fd);
printf("Connection closed\n");
/* remove the FIFO */
unlink(myfifo);
return 0;
}
读取管道:
#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
main() {
int fd;
fd_set set_a;
char * myfifo = new char [12];
strcpy(myfifo, "./tmp/myfifo1");
char buffer[1024];
fd = open("./tmp/myfifo1", O_RDONLY | O_NONBLOCK);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
ssize_t bytes;
size_t total_bytes = 0;
printf("\nDropped into read pipe\n");
while(1){
if((bytes = read(fd, buffer, sizeof(buffer))) > 0){
std::string message(&buffer[22]);
total_bytes += (size_t)bytes;
printf("%i", bytes);
printf("Message: %s\n", message.c_str());
memset(&buffer[0], 0, sizeof(buffer));
}else{
if (errno == EWOULDBLOCK) {
printf("\ndone reading (%d bytes)\n", (int)total_bytes);
//break;
}
printf("No message\n");
sleep(2);
}
}
return EXIT_SUCCESS;
}
我觉得命名管道的行为非常不灵活,这是我通过测试程序发现的。首先,如果没有读取进程附加到 fifo 管道,则除了写入管道的最后一条消息之外的所有消息都会丢失(或者一般来说,在读取进程附加到管道后只能读取最后一条消息)。如果您将多条消息写入管道,则读取之间的所有消息(例如轮询)将被解释为一条消息(我知道它们可以被 \0 分割)。
命名管道的主要目标是a)系统日志和b)用户身份验证。命名管道的异步非常适合我的需要。但无论如何,我不确定命名管道是否是不同程序之间 IPC 的最佳解决方案。另外,我不确定上述行为是否正常,或者我是否以错误的方式使用命名管道。我也考虑过套接字,但随后我会遇到巨大的阻塞问题。
感谢您的帮助。