0

My main thread looks like this:

while (!shouldExit) {
   int c = getchar();
   switch (c) {
     case .... :
     case .... :
     case 'x' : shuoldExit = true; break;
   }
}

Then , there is another thread that reads data from the network, and when I get a special command it sets shouldExit = 1. This works perfectly, the only problem is that getchar() according to strace keeps blocking on read(0).

How can my working thread abort the read system call in the main thread?

I tried sending signals to myself, but that just kills the application (expected). When I trap the signals in a null handler the app keeps alive, but the read keeps blocking.

One option might be to use select() , but I am not happy about it. Any alternatives?

EDIT: See also this question, which is similar to mine, but we are searching for different solutions. His solution is not applicable to my problem, as the blocking read() is on the main thread.

aborting a blocking read on linux

Community
  • 1
  • 1
elcuco
  • 8,948
  • 9
  • 47
  • 69

1 Answers1

3

Use pthread_kill() on the thread you want to signal. Don't use kill(); for that matter, since you linked to it, don't use signal() -- it's one of the more retarded, non-portable interfaces:

The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead. See Portability below."

[ This has been answered in the comments, but for some reason still shows up in the relevance top of unanswered questions. So here, for the sake of completeness ]

dan3
  • 2,528
  • 22
  • 20
  • mmm... yes, but this solution is also ugly, since it will loose allocated memory on my working thread. I want to "signal" that thread, so it can do its own garbage collection. – elcuco Sep 14 '13 at 11:51
  • pthread_kill() doesn't kill. It sends a signal. You don't have to send SIGINT, you can use any signal. And in any case kill() and pthread_kill() only "kill" when you haven't set a handler. To set the **signal handler** for the thread, use sigaction(). Also use pthread_sigmask() to select which thread receives the signal. Read up on the man pages for pthread_kill(), pthread_sigmask() and sigaction(). – dan3 Sep 14 '13 at 13:05