Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a blocking thread in C's pthread gracefully?

Say I have a thread that's something like this:

void my_thread(char *device_name) {
    int fd = open(device_name, O_RDONLY);
    struct input_event ev;

    while(1) {
        read(fd, &ev, sizeof(struct input_event));
        /* do something */
    }
}

How do I stop such a thread? One way is using pthread_cancel, but I'd rather do it more gracefully. Something like pthread_kill perhaps? In such case, however, would the read method unblock (as I presume it should) and how would the thread handle the signal? Or is it the process that should handle it?

I'd be very grateful for an advice!

like image 580
Albus Dumbledore Avatar asked Jun 14 '11 10:06

Albus Dumbledore


1 Answers

The answer to this is to not do anything that will block without a timeout. For IO, you shouldn't call read() until you know the call will not block. For example, use poll() or select() on the path first in order to determine the status.

like image 68
mah Avatar answered Sep 17 '22 17:09

mah