对上一篇进行改进,变成可以接收键盘输入,然后写入管道:
读端代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <fcntl.h>
void read_cb(evutil_socket_t fd, short what, void* arg) {
//把管道中的数据读出到buf中,然后打印出来
char buf[1024] = {0};
int len = read(fd,buf,sizeof(buf));
printf(“data len= %d , buf= %s\n”,len,buf);
printf(“read event: %s\n”, what & EV_READ ? “YES” : “NO”);
}
int main(int argc, const char* argv[])
{
//先删除同名管道,再创建管道
unlink(“myfifo”);
mkfifo(“myfifo”, 0664);
int fd = open("myfifo", O_RDONLY | O_NONBLOCK);
if(-1 == fd) {
perror("create fifo pipe fail");
exit(1);
}
//创建事件框架,事件的根结点
struct event_base* base = NULL;
base = event_base_new();
//创建事件
struct event* ev = NULL;
ev = event_new(base, fd, EV_READ | EV_PERSIST, read_cb, NULL);
//往事件框架中添加事件ev
event_add(ev,NULL);
//分发事件
event_base_dispatch(base);
//释放资源
event_free(ev);
event_base_free(base);
close(fd);
return 0;
}
写端代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <fcntl.h>
void read_terminal(int fdd, short what, void * arg)
{
//先读终端fdd的内容到buf中,在输出到pipe中
char buf[1024] = {0};
int len = read(fdd, buf, sizeof(buf));
int fd = *(int *)arg;
write(fd, buf, strlen(buf)+1);
}
void write_cb(evutil_socket_t fd, short what, void* arg) {
//把数据写到buf中,然后写到管道中,然后打印出来
// char buf[1023] = {0};
// static int num = 0;
//sprintf(buf, “hello world == %d \n”, num++);
//write(fd, buf, strlen(buf)+1);
//printf(“pipe can be write\n”);
}
int main(int argc, const char* argv[])
{
//管道已经在read_fifo.c中创建管道
int fd = open("myfifo", O_WRONLY | O_NONBLOCK);
if(-1 == fd) {
perror("create fifo pipe fail");
exit(1);
}
//创建事件框架,事件的根结点
struct event_base* base = NULL;
base = event_base_new();
//创建事件
struct event* ev = NULL;
ev = event_new(base, fd, EV_WRITE | EV_PERSIST, write_cb, base);
//往事件框架中添加事件ev
event_add(ev,NULL);
//pipe可写,创造终端事件,把它加入到事件框架
struct event* stdin_ev = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST, read_terminal,&fd);
event_add(stdin_ev, NULL);
//分发事件
event_base_dispatch(base);
//释放资源
event_free(ev);
event_base_free(base);
close(fd);
return 0;
}