gpt4 book ai didi

c - 如何在不轮询的情况下查找文件中的更改?

转载 作者:行者123 更新时间:2023-11-30 17:27:47 24 4
gpt4 key购买 nike

我有一个 Beagle 骨头,想从我的程序中读取 GPIO 引脚。该文件在任何给定时刻都包含 1 或 0。在我的 C 程序中,我有一个 while 循环,它通过一个 sleep 函数永远运行,以防止它在该引脚为低电平 (0) 时和当该引脚为高电平 (1) 时运行代码。我觉得这非常浪费资源。有没有办法让我看到这个文件何时为 1 然后运行代码?我不喜欢轮询,尤其是当小猎犬骨头将由电池供电时。

最佳答案

使用通知机制,例如利用libev .

基本思想是,如果数据可用,则调用回调。

如果这不起作用,您可能需要使用其他 API 才能到达那里,例如 inotify。

libev 文档提供的示例:

// a single header file is required
#include <ev.h>

#include <stdio.h> // for puts

// every watcher type has its own typedef'd struct
// with the name ev_TYPE
ev_io stdin_watcher;
ev_timer timeout_watcher;

// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void
stdin_cb (EV_P_ ev_io *w, int revents)
{
puts ("stdin ready");
// for one-shot events, one must manually stop the watcher
// with its corresponding stop function.
ev_io_stop (EV_A_ w);

// this causes all nested ev_run's to stop iterating
ev_break (EV_A_ EVBREAK_ALL);
}

// another callback, this time for a time-out
static void
timeout_cb (EV_P_ ev_timer *w, int revents)
{
puts ("timeout");
// this causes the innermost ev_run to stop iterating
ev_break (EV_A_ EVBREAK_ONE);
}

int
main (void)
{
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;

// initialise an io watcher, then start it
// this one will watch for stdin to become readable
ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
ev_io_start (loop, &stdin_watcher);

// initialise a timer watcher, then start it
// simple non-repeating 5.5 second timeout
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
ev_timer_start (loop, &timeout_watcher);

// now wait for events to arrive
ev_run (loop, 0);

// break was called, so exit
return 0;
}

关于c - 如何在不轮询的情况下查找文件中的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26265363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com