How can I cancel a blocked read/recvfrom system call on vxworks or linux

房东的猫 提交于 2019-12-13 12:22:35

问题


In TASK I:

...

while (1)
{
  if (running == false)
  break;
  ret = read(fd, buf, size); /* Or: ret = recvfrom(sock, buf, size, 0, NULL, NULL); */
  ...
 }

In task II:

...
running = true;
/* ioctl(fd, FIOCANCEL, 0); */
close(fd);   /* Or: close(sock);*/

what should do in task II to cancel the blocked task I,

In vxworks, there is a function, ioctl(fd, FIOCANCEL, 0) to cancel a blocked read or write but it can not work. Probably because the driver can not support "FIOCANCEL".

how to write task II in vxworks and linux? or are there any other way to do my task?


回答1:


Cancelling a read/recvfrom call is impossible on linux. You cannot write these tasks using the same API. On Linux you can use epoll and O_NONBLOCK to create the semantics of canceling a read/recvfrom.

It is impossible to do this using the same code for both linux and vxworks.




回答2:


Don't use blocking IO, this is a classic case of creating a thread with no (reachable) exit condition, which I consider to be a bug. The easiest example of how you should run your thread is as follows:

volatile bool _threadRunning = true;

void taskI()
{
    int flags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);

    while (_threadRunning == true)
    {
        ret = read(fd, buf, size);
        if (ret > 0)
        {
            // process buffer
        }
        else
        {
            // sleep for 1 millisecond or so...
        }
    }
    close(fd);
}


void taskII()
{
    _threadRunning = false;
    _taskI.join();
}


来源:https://stackoverflow.com/questions/17781516/how-can-i-cancel-a-blocked-read-recvfrom-system-call-on-vxworks-or-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!