[英]issue in C with read after epoll_wait in a pthread
我正在為嵌入式 ARM 系統開發 C 中的 MQTT 客戶端應用程序,該系統必須基於 GPIO 更改發送消息。
為此,我嘗試啟動一個執行epoll_wait
的pthread
並read
/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.