有名管道(mkfifio)

15 篇文章 0 订阅

有名管道(mkfifio)

前言

我们在日常开发中,经常会获取用户输入,来触发app的执行不同的功能。
获取用户输入,首先肯定想到的是scanf或者fges等方法,但是这些函数有一个特点就是不能放到后台执行,放后台了还怎么获取输入呢?
其实我们可以用linux中的有名管道来实现这个功能。

linux中有很多IPC的方式,都可以实现这个功能,这里只是抛砖引玉罢了。

代码示例

以下代码就是一个简单的示例,在后台运行这段代码,然后在终端输入
echo "h" > /tmp/mkfifio
就可以和fifo进行通讯,

这种方法有以下优点(最主要的就是方便)

  1. 用echo输入,省去了做一个client
  2. 只需把下面这段代码嵌入到自己的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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chasentech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值