有名管道(mkfifio)
前言
我们在日常开发中,经常会获取用户输入,来触发app的执行不同的功能。
获取用户输入,首先肯定想到的是scanf或者fges等方法,但是这些函数有一个特点就是不能放到后台执行,放后台了还怎么获取输入呢?
其实我们可以用linux中的有名管道来实现这个功能。
linux中有很多IPC的方式,都可以实现这个功能,这里只是抛砖引玉罢了。
代码示例
以下代码就是一个简单的示例,在后台运行这段代码,然后在终端输入
echo "h" > /tmp/mkfifio
就可以和fifo进行通讯,
这种方法有以下优点(最主要的就是方便)
- 用echo输入,省去了做一个client
- 只需把下面这段代码嵌入到自己的app中,就可以进行通信
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#define FIFO_NAME "/tmp/mkfifio"
void *thread_fun(void *arg)
{
unlink(FIFO_NAME);
int ret = mkfifo(FIFO_NAME, 0777);
if (ret < 0)
{
perror("mkfifo failed!\n");
return 0;
}
int fd = open(FIFO_NAME, O_RDONLY);
if (fd < 0)
{
perror("open failed");
return 0;
}
printf("PIPE_BUF = %d\n", PIPE_BUF);
while (1)
{
char buf[30] = {0};
memset(buf,0,sizeof(buf));
if (read(fd, buf, sizeof(buf)) < 0)
perror("read failed");
printf("%s", buf);
//printf("rece is %s", buf); //failed sleep
//printf("%s\n", buf); //failed
if (buf[0] == 'h')
{
printf("support cmd:\n");
printf("\t1: test1\n");
printf("\t2: test2\n");
printf("\tq: to quit\n");
}
if (buf[0] == '1')
{
printf("in test1\n");
}
if (buf[0] == '2')
{
printf("in test2\n");
}
if (buf[0] == 'q')
break;
}
close(fd);
unlink(FIFO_NAME);
}
int main()
{
pthread_t ntid_rece;
pthread_create(&ntid_rece, NULL, thread_fun, NULL);
while (1)
{
sleep(1);
}
pthread_join(ntid_rece, NULL);
return 0;
}