close

The image “http://doc.trolltech.com/4.0/images/qt-logo.png” cannot be displayed, because it contains errors.   Starting interactive processes with QProcess

interactive file I/O in Qt 的處理機制 & POSIX dup(2) - Linux-specific 特性

I've been playing with QProcess quite a bit lately, which is a wonderful class. However, I noticed that I cannot start an interactive process with it (i.e. a process that gets stdin from the terminal). This is because QProcess redirects stdin for all processes it starts back to the parent process, so that the programmer can send data to the process using write(). Thing is, I don't want this. So, after talking a bit with Andreas (who wrote QProcess), we came up with the following trick:

class InteractiveProcess : public QProcess
{
static int stdinClone;
public:
InteractiveProcess(QObject *parent = 0)
: QProcess(parent)
{
if (stdinClone == -1)
stdinClone = ::dup(fileno(stdin));
}
protected:
void setupChildProcess()
{
::dup2(stdinClone, fileno(stdin));
}
};
 
int InteractiveProcess::stdinClone = -1;

Basically, we clone stdin in the parent process, and in the child (which calls our QProcess::setupChidProcess() reimplementation), we redirect stdin to the clone created by the parent.

Pretty neat, isn't it? :)

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Bluelove1968 的頭像
    Bluelove1968

    藍色情懷

    Bluelove1968 發表在 痞客邦 留言(0) 人氣()