Reputation: 3253
How can a read Linux system call be unblocked in C++? If I have for example in a thread the following loop :
bool shouldRun;
void foo(){
while(shouldRun){
length = read( file_descriptor, buffer, buffer_length);
//do something
}
return;
}
main(){
shouldRun = true;
std::thread myThread(foo);
//do some other stuff
shouldRun = false;
//-->here I want to unblock "read" in foo
}
Generally the read method should block, I only want to unblock it when needed.
Upvotes: 2
Views: 6368
Reputation: 115
I'm going to assume that the read call is waiting for data to become available and it's blocking because of this.
That's why I'd suggest you check if data is available before reading:
#include <sys/ioctl.h>
...
int count;
ioctl(file_descriptor, FIONREAD, &count);
Upvotes: 0
Reputation: 3911
the libc read() function internally invoke syscall in kernel side. The (linux) kernel region is generally not support abort due to its design (yes this can make process non-killable in some case)
To archive your goal, you should make read() non-blocking so that the kernel call return immediately, or check if data ready before read() using select().
Upvotes: 0
Reputation: 28892
call
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
This will make the file descriptor non-blocking.
Upvotes: 3