繁体   English   中英

C 中的问题,在 pthread 中的 epoll_wait 之后读取

[英]issue in C with read after epoll_wait in a pthread

我正在为嵌入式 ARM 系统开发 C 中的 MQTT 客户端应用程序,该系统必须基于 GPIO 更改发送消息。

为此,我尝试启动一个执行epoll_waitpthreadread /sys/class/gpio/gpio<x>/value以获取更改值。

第一步是将 gpio 配置为输入和边缘:

root@ad:~# cat /sys/class/gpio/gpio13/direction
in
root@ad:~# cat /sys/class/gpio/gpio13/edge
both

第二步,是在main function中启动pthread。(运行prthread后,main会进入一个循环来管理MQTT通信):


// Main
int main(int argc, char *argv[]) {

    Network n;
    MQTTClient c;
(...)

    toStop = false;
    
    pthread_create(&thread_id, NULL, detection, NULL);
        
    while (!toStop)
    {
        MQTTYield(&c, 100);

        (...MQTT stuff...)
    }
    
    
    // stop thread if exists
    if(thread_id)
    {
        pthread_cancel(thread_id);
        
        thread_id = NULL;
    }

(...)
}

然后 pthread 运行以下 function:


// detection function call as pthread
void *detection(void *args){

    char strvalue[1];
    int ret;
    int nn;
    int ep;
    int fd;

    struct epoll_event ev, events;

    
    ep = epoll_create1(0);
    
    fd = open("/sys/class/gpio/gpio13/value", O_RDONLY);
    
    nn = read(fd, &strvalue, 1);
    
    if (nn > 0) {
        printf("Initial value = %c\n", strvalue[0]);
        lseek(fd, 0, SEEK_SET);
    }
    
    ev.events = EPOLLIN | EPOLLET; // EPOLLPRI;
    ev.data.fd = fd;


    ret = epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev);
    printf("ret=%d\n", ret);
    
    while (1)
    {
        printf("Waiting\n");
        
        ret = epoll_wait(ep, &events, 1, -1);
        printf("ret=%d\n", ret);
        
        if(ret > 0) {
            lseek(fd, 0, SEEK_SET);
            printf("fd=%d\n", events.data.fd);

            nn = read(events.data.fd, &strvalue, 1);
            printf("nn=%d\n", nn);
            
            printf("value = %c\n", strvalue[0]);
        }
        
    }
    
}

问题是当 gpio 改变时,epoll_wait 得到它,但线程在read期间停止

这是 output:

Initial value = 1
ret=0
Waiting
ret=1
fd=7
nn=1
value = 1
Waiting
ret=-1
Waiting
ret=1
fd=7

如果我在 main 中直接调用 function *detection (因此没有 pthread),一切都运行良好。

如何解决这个问题?

具体问题。 thread_id变量名称已在包含的其他 c 代码中使用,但编译器不会发出警告。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM