January 24, 2005

Preserving stdin when using SDL

SDL has a "feature" where by it redirects stdin/out/err on certain platforms, including OS X. This presented problems since tcprose (an opengl network visualiser) depended on stdin for interprocess communication. After much mucking about, I arrived eventually at a 3 line solution to the problem:

First we duplicate the stdin file descriptor so when SDL calls close() on 0 the stream remains open.
int dup_fd = dup(0);
Then we initalise SDL, and let it redirect stdin as it does.
Here is where we do our little trick: close 0, then duplicating the original stdin stream back onto 0, so scanf etc will continue to work.
And viola! We have stdin back again, no longer redirected. This solution won't work for window users though. See discussion at gmane.org.