linux下,用libevent 写一个 监听匿名管道,用于多线程通讯的代码
时间: 2024-05-10 22:18:36 浏览: 17
下面是一个简单的示例代码,演示如何使用libevent在Linux下监听匿名管道并进行多线程通信:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <event2/event.h>
#include <pthread.h>
#define PIPE_NAME "/tmp/my_pipe"
#define MAX_MSG_LEN 256
struct event_base *base;
struct event *pipe_event;
void read_cb(evutil_socket_t fd, short event, void *arg)
{
char msg[MAX_MSG_LEN];
int len;
len = read(fd, msg, MAX_MSG_LEN - 1);
if (len <= 0) {
perror("read");
exit(1);
}
msg[len] = '\0';
printf("Received %d bytes: %s", len, msg);
}
void *thread_func(void *arg)
{
char msg[MAX_MSG_LEN];
int len;
int pipe_fd;
pipe_fd = open(PIPE_NAME, O_WRONLY);
if (pipe_fd == -1) {
perror("open");
exit(1);
}
while (1) {
printf("Enter message: ");
fgets(msg, MAX_MSG_LEN, stdin);
len = strlen(msg);
if (len > 0 && msg[len-1] == '\n') {
msg[len-1] = '\0';
len--;
}
if (len == 0)
continue;
if (write(pipe_fd, msg, len) == -1) {
perror("write");
exit(1);
}
}
}
int main(int argc, char **argv)
{
int pipe_fd;
pthread_t thread_id;
unlink(PIPE_NAME);
if (mkfifo(PIPE_NAME, S_IRUSR | S_IWUSR) == -1) {
perror("mkfifo");
exit(1);
}
pipe_fd = open(PIPE_NAME, O_RDONLY | O_NONBLOCK);
if (pipe_fd == -1) {
perror("open");
exit(1);
}
base = event_base_new();
if (!base) {
perror("event_base_new");
exit(1);
}
pipe_event = event_new(base, pipe_fd, EV_READ | EV_PERSIST, read_cb, NULL);
if (!pipe_event) {
perror("event_new");
exit(1);
}
if (event_add(pipe_event, NULL) == -1) {
perror("event_add");
exit(1);
}
if (pthread_create(&thread_id, NULL, thread_func, NULL) != 0) {
perror("pthread_create");
exit(1);
}
event_base_dispatch(base);
return 0;
}
```
该代码创建了一个名为`/tmp/my_pipe`的匿名管道,并使用libevent在主线程中监听该管道的读事件。当管道中有数据可读时,会自动调用`read_cb`函数进行处理。
同时,该程序还创建了一个新的线程,在该线程中不断从标准输入读取用户输入的消息,并将其写入管道中。
在运行该程序后,可以在标准输入中输入消息并回车,然后在主线程中就会收到相应的消息。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)