How to use a pipe with select after forking and executing? - c++

I'm a noob to linux programming, so please bear with me. In my application, I fork(), then execl() another binary after having setup a single pipe for reading in. After the fork and exec are OK, i do a dup2() for reading in from the stdout of the executed binary. I need my parent application to wait for output from the process it has created and once there is output, read it. I figured I will use select(), and wait for a few milliseconds before trying to see if there is data to be read and if there is, use read(). However my code does not work because select() takes as argument an fd_set, while my pipe is of int converted by pipe() and dup2(). What can I do to overcome this and is there another alternative? Note, I'm not blocking the parent process until the process ends, but want to read info while the child process runs.

To use select() you must create a struct fd_set and populate it using the FD_ macros. In this way you will inform the function which descriptors you are interested in (note that it is common to be interested in several at once). For example:
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(your_input_fd, &rfds);
int retval = select(your_input_fd + 1, &rfds, NULL, NULL, NULL);
The first argument to select is to be the highest-numbered file descriptor you are interested in, plus one. That, along with example code, is explained here:
http://linux.die.net/man/3/fd_set

Related

Best way to exit application at CTRL+C interrupt on Linux. (C/C++)

My application checks for user input in its main thread:
while (running)
{
std::string console;
if (std::getline(std::cin, console))
{
process(&console);
}
}
Before that I have setup a sigaction to detect CTRL+C in conjunction with a function handler to shutdown other threads.
Now, when a SIGINT occurs the application crashes; GDB output:
I was looking around and found other solutions such as non-blocking input reading: (pseudo-code)
while (running)
{
if (input_avail())
{
getinput
process
}
else
sleep(1);
}
But even that fails for me at the sleep function (nanosleep):
So I'm quite curious on how other people achieve this?
(Using g++ v4.8.2 Kernel 3.10)
Additional info requested:
Before the main thread loop:
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = signalinfo;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGTERM, &sigIntHandler, NULL);
sigaction(SIGQUIT, &sigIntHandler, NULL);
sigaction(SIGINT, &sigIntHandler, NULL);
Signal handler:
void signalinfo(int signum)
{
// Only setting a flag so threads know to exit.
pCore->Termination(signum);
}
Not sure if it answers your question, but the documentation of the XBoard protocol explains some common strategies how engine engine handle reading from stdin.
It basically sketches how you might implement your non-blocking pseudo code.
Source: XBoard protocol (6. Hints on input/output)
... on the input side, you are likely to want to poll during your search and stop it if new input has come in. If you implement pondering, you'll need this so that pondering stops when the user makes a move. You should also poll during normal thinking on your move, so that you can implement the "?" (move now) command, and so that you can respond promptly to a "result", "force", or "quit" command if xboard wants to end the game or terminate your engine. Buffered input makes polling more complicated -- when you poll, you must stop your search if there are either characters in the buffer or characters available from the underlying file descriptor.
The most direct way to fix this problem is to use unbuffered operating system calls to read (and poll) the underlying file descriptor directly. On Unix, use read(0, ...) to read from standard input, and use select() to poll it. See the man pages read(2) and select(2). (Don't follow the example of GNU Chess 4 and use the FIONREAD ioctl to poll for input. It is not very portable; that is, it does not exist on all versions of Unix, and is broken on some that do have it.) On Win32, you can use either the Unix-like _read(0, ...) or the native Win32 ReadFile() to read. Unfortunately, under Win32, the function to use for polling is different depending on whether the input device is a pipe, a console, or something else. (More Microsoft brain damage here -- did they never hear of device independence?) For pipes, you can use PeekNamedPipe to poll (even when the pipe is unnamed). For consoles, you can use GetNumberOfConsoleInputEvents. For sockets only, you can use select(). It might be possible to use WaitForSingleObject more generally, but I have not tried it. Some code to do these things can be found in Crafty's utility.c, but I don't guarantee that it's all correct or optimal.
A second way to fix the problem might be to ask your I/O library not to buffer on input. It should then be safe to poll the underlying file descriptor as described above. With C, you can try calling setbuf(stdin, NULL). However, I have never tried this. Also, there could be problems if you use scanf(), at least with certain patterns, because scanf() sometimes needs to read one extra character and "push it back" into the buffer; hence, there is a one-character pushback buffer even if you asked for stdio to be unbuffered. With C++, you can try cin.rdbuf()->setbuf(NULL, 0), but again, I have never tried this.
A third way to fix the problem is to check whether there are characters in the buffer whenever you poll. C I/O libraries generally do not provide any portable way to do this. Under C++, you can use cin.rdbuf()->in_avail(). This method has been reported to work with EXchess. Remember that if there are no characters in the buffer, you still have to poll the underlying file descriptor too, using the method described above.
A fourth way to fix the problem is to use a separate thread to read from stdin. This way works well if you are familiar with thread programming. This thread can be blocked waiting for input to come in at all times, while the main thread of your engine does its thinking. When input arrives, you have the thread put the input into a buffer and set a flag in a global variable. Your search routine then periodically tests the global variable to see if there is input to process, and stops if there is. WinBoard and my Win32 ports of ICC timestamp and FICS timeseal use threads to handle multiple input sources.

alternatives to PeekNamePipe() with anonymous pipe -- WIN32

I have a program that launch another console program as its child process and communicate with it using anonymous pipe. I redirected both its stdin and stdout. The pseudocode is like:
// Create pipes for stdin and stdout
CreatePipe(&std_in_rd, &std_in_wr, NULL, 0);
CreatePipe(&std_out_rd, &std_out_wr, NULL, 0);
// redirection
startup_info.hStdOutput = std_out_wr;
startup_info.hStdInput = std_in_rd;
// create the process
CreateProcess(...);
// send command to the child process.
WriteFile(hWriteStdin, ...);
// receive feedback from the child process.
ReadFile(hReadStdout, ...);
But, the child process's processing the commands needs time, and I don't know how much time I should wait to get its output.
I used a loop that calls PeekNamedPipe to examine whether I can read from the pipe, but this method is not good for it consums a lot CPU.
The child process was not written by me and I can't modify its code.
How can I get informed when the child process has finished writing, like a hook?
Thanks.
You should try using ReadFileEx() to read from the pipe asynchronously.

Porting Windows-Centric Console I/O To Linux

I am developing a Windows application that has a separate thread for processing user (or 3rd party) application input via stdin.
This thread is designed such that it waits via WaitForMultipleObjects on two events:
A death signal. When this signal is raised, the interface-processing thread shuts down.
An interface signal. When this signal is raised, there is input ready to be read. The input is read and processed.
Under Windows this thread enters a main loop where it Waits for these 2 events (where bWaitAll is FALSE). Waiting on the stdin handle has the effect of signaling when there is input ready to be read, and the other event is set from elsewhere in the application.
This works exactly as I want. It waits for an event to be raised without entering in to a busy-wait, and it waits for both event simutaneously.
I wish to port this functionality to Linux, but I'm not sure how to achieve the desired result. Fundamentally, what I really want is this:
Under Linux, how do I design a thread so that it will respond
immediately to user-input on stdin, yet it can also respond
immediately to a kill-flag being raised from elsewhere in the
application?
In order to accomplish the latter, it seems to me that I cannot use cin, gets, getch or any other function that blocks until the user has entered text. Yet I do not know how to read user input in a console-based application without blocking.
I'm open to any change in architecture (if there's a more Linux-y way to do this) that include having user input processed in a separate thread that can be terminated from elsewhere in the application. I'm using GCC 4.4, and Boost 1.51.
The standard way of doing this in Linux is to use the select(2) system call. However, select is more limited than WaitForMultipleObjects, in that it can only wait on file descriptors, not other kinds of objects (such as events). So, the typical way of working around that is to create a pipe and write a dummy value to the pipe as your "signal".
Something like this:
// Error checking omitted for expository purposes
int pipefd[2];
pipe(pipefd); // Create the pipe
while(1)
{
// Create file descriptor set of stdin and the read end of the pipe
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
FD_SET(pipefd[0], &fds);
int maxfd = MAX(STDIN_FILENO, pipefd[0]);
// Wait until input becomes available on either stdin or the pipe
int num_available = select(&fds, NULL, NULL, NULL);
// Read & process stdin if possible (will not block)
if (FD_ISSET(STDIN_FILENO, &fds))
{
int n = read(STDIN_FILENO, buffer, size);
...
}
// Read & process pipe if possible (will not block)
if (FD_ISSET(pipefd[0], &fds))
{
char dummy;
read(pipefd[0], &dummy, 1);
// Handle signal (e.g. break out of loop)
}
}
Then to signal to the thread that it's done, just write a single byte to the write end of the pipe:
char dummy = 42;
write(pipefd[1], &dummy, 1);
libev (and several similar incarnations) offers a convenient abstraction around select including being able to pend on signals.
If you have the option to alter the origin of "An interface signal" then you could consider changing it to use raise instead.

using fgets as non-blocking function c++

I'm writing a program that reads in a loop from the stdin, using the function fgets, as follows:
while(fgets(buffer2, BUFFERSIZE , stdin) != NULL){
//Some code
}
I want my code to be non-blocking, that is: I don't want the program to hold on the 'fgets' line when there's no input at the moment from the user.
How can i do it?
fgets() is a blocking function, it is meant to wait until data is available.
If you want to perform asynchronous I/O, you can use select(), poll(), or epoll(). And then perform a read from the file descriptor when there is data available.
These functions use the file descriptor of the FILE* handle, retrieved by:
int fd = fileno(f);
If you are using Unix or Linux, then one solution can be to mark the file descriptor used by the file to be non-blocking. Example:
#include <fcntl.h>
FILE *handle = popen("tail -f /als/als_test.txt", "r");
int fd = fileno(handle);
flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
fgets should be non-blockng now and will return a null and set an error code for you.
If you have a proper POSIX environment, you can use select() or poll() to check for input on stdin's descriptor before calling fgets()... read().
Jan's comment below (thanks!) explains why you can't use fgets() with this approach... summarily, there's an extra layer of buffering in the FILE object, and data can already be waiting in though the select() finds nothing more on the file descriptor... preventing your program from responding in a timely way, and potentially hanging if some other system is waiting for a response to already sent data before sending more on stdin.
You basically have two options:
Run that loop in a separate thread.
Check if your OS supports some API for non-blocking IO.
This would sound a little like overkill, but this is the one, that comes to my mind.
Use 2 different threads - one using this loop and waiting blocking ( I don't think that this could be done non-blocking). And when something is read, push it into a pipe.
Meanwhile, the other thread will do whatever it needs to do and check for data in the pipe from time to time ( apparently, you want this to be asynchronous, or at least I get it this way. If so, this means different threads )
But then, you'll need to synchronize the two threads very well. You should check your OS about multithreading and IO operations.
On Linux, you can specify the end of input by pressing ctrl-d, and of-course you can do this using separate thread.

How do I read stdout/stderr output of a child process correctly?

I have written a program a.exe which launches another program I wrote, b.exe, using the CreateProcess function. The caller creates two pipes and passes the writing ends of both pipes to the CreateProcess as the stdout/stderr handles to use for the child process. This is virtually the same as the Creating a Child Process with Redirected Input and Output sample on the MSDN does.
Since it doesn't seem to be able to use one synchronization call which waits for the process to exit or data on either stdout or stderr to be available (the WaitForMultipleObjects function doesn't work on pipes), the caller has two threads running which both perform (blocking) ReadFile calls on the reading ends of the stdout/stderr pipes; here's the exact code of the 'read thread procedure' which is used for stdout/stderr (I didn't write this code myself, I assume some colleague did):
DWORD __stdcall ReadDataProc( void *handle )
{
char buf[ 1024 ];
DWORD nread;
while ( ReadFile( (HANDLE)handle, buf, sizeof( buf ), &nread, NULL ) &&
GetLastError() != ERROR_BROKEN_PIPE ) {
if ( nread > 0 ) {
fwrite( buf, nread, 1, stdout );
}
}
fflush( stdout );
return 0;
}
a.exe then uses a simple WaitForSingleObject call to wait until b.exe terminates. Once that call returns, the two reading threads terminate (because the pipes are broken) and the reading ends of both pipes are closed using CloseHandle.
Now, the problem I hit is this: b.exe might (depending on user input) launch external processes which live longer than b.exe itself, daemon processes basically. What happens in that case is that the writing ends of the stdout/stderr pipes are inherited to that daemon process, so the pipe is never broken. This means that the WaitForSingleObject call in a.exe returns (because b.exe finished) but the CloseHandle call on either of the pipes blocks because both reading threads are still sitting in their (blocking!) ReadFile call.
How can I solve this without terminating both reading threads with brute force (TerminateThread) after b.exe returned? If possible, I'd like to avoid any solutions which involve polling of the pipes and/or the process, too.
UPDATE: Here's what I tried so far:
Not having b.exe inherit a.exe; this doesn't work. the MSDN specifically says that the handles passed to CreateProcess must be inheritable.
Clearing the inheritable flag on stdout/stderr inside b.exe: doesn't seem to have any effect (it would have surprised me if it did).
Having the ReadDataProc procedure (which reads on both pipes) consider whether b.exe is actually running in addition to checking for ERROR_BROKEN_PIPE. This didn't work of course (but I only realized afterwards) because the thread is blocked in the ReadFile call.
Use named pipe and asynchronous ReadFile
or
Parse the output read from the pipe looking for the end (it may be too complicated in your case).
What happens in that case is that the
writing ends of the stdout/stderr
pipes are inherited to that daemon
process, so the pipe is never broken.
Daemons should close their inherited file descriptors.
Is seems that on Windows versions prior to Windows Vista (where you can use the CancelSynchronousIO function, there is no way around terminating the reading threads using TerminateThread.
A suitable alternative (suggested by adf88) might be to use asynchronous ReadFile calls, but that's not possible in my case (too many changes to the existing code required).
set some global flag (bool exit_flag) and write something to pipe in a.exe