I have the following situation: two applications, "interface" (Qt) and "center" (C), work together as part of a embedded Linux solution communicating mainly by sockets. "Interface" starts "center" and must be able to send a "close" command to it. "Center" has a main event loop where it should constantly read if the "close" command was send by the "interface".
First I would call "Center" with system("./center&")
and I would use read()
in the following way:
char readBuffer[10];
memset(readBuffer,'\0',sizeof(char) * 10);
read(STDIN_FILENO, readBuffer, 10);
if (strcmp(readBuffer, "close") == 0)
{
DEBUG_MAIN("CENTER: Closing center normally");
break;
}
(this inside a while(true)
loop in main()
).
The problem is that this way "Interface" unable to communicate directly to "Center" - I can only use the socket system. That would work fine, but it seems it would have some drawbacks: the socket is read from another thread, so I'll have to create mutex etc. to constantly see a bool flag inside main()
, the call to the ill-advised system
, etc..
So I decided that instead I should call "Center" with QProcess, what would give me some logging advantages and I would have the traditional QProcess way of communicating with that app, namely writing to the stdin with write()
.
So I did implemented QProcess successfully and everything is working fine with the exception that now the code copied above with read()
became a blocking one: when calling "Center" with system()
, the code would pass that part noticing there was nothing in STDIN to be read. Now that I call Center
with QProcess, read()
is behaving in a blocking way.
So my first (and specific) question is: why read()
behaves in non-blocking fashion when "Center" is started with system()
but blocking when is started with QProcess?
And the second (generic) question is: how can I read from STDIN in a non-blocking way? I already did this research before (example of results) and AFAIR the code above was the solution I got for doing this; this is why I was using it.
Answer to the second question: to read the STDIN in a non-blocking way, just write
#include <fcntl.h>
int flagsTemp = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flagsTemp | O_NONBLOCK);