user440297
user440297

Reputation: 1181

QProcess.startDetached() and write to its stdin

What is wrong with this code? I can not write to stdin of new process that has been detached. It is important for me that the new process is detached.

QProcess commandLine;
commandLine.setWorkingDirectory("E:\\");  //does not work.
commandLine.startDetached("cmd.exe");     //works (but uses wrong working dir).
commandLine.write("echo hi\0");           //writes nothing.
commandLine.write("\n\r");                //Still nothing is written!

Upvotes: 4

Views: 6890

Answers (2)

Catty2327
Catty2327

Reputation: 77

call static method with arguments doesn't provide any set of process into child command.

process.startDetached(command)

try this:

QProcess process;
process.setProgram(fileName);
process.setArgument(argsList);
process.setWorkingDirectory(dirName);
process.startDetached();

Upvotes: 0

Dariusz Scharsig
Dariusz Scharsig

Reputation: 1220

Good morning.

The problem is that QProcess::startDetached() is a static method which creates a "fire and forget" process.

This means, that you cannot set a working directory this way. All you can do is call

QProcess::startDetached (const QString &program, const QStringList &arguments, const   QString &workingDirectory);

This however leaves you with the problem of writing to the stdin of the newly created process. The thing is, since you don't have a QProcess object there is nothing you can write your stdin to. There could be a solution using the process handle the static startDetached() method's providing.

We had the similar problem in our company. We needed detached processes which ran beyond the lifespan of the calling programm and for which we could set the environment. This seemed, looking at the Qt code, impossible.

My solution was to use a wrapper around QProcess with its own startDetached() method. What it did, it actually created this QProcess subclass on the heap and used its ordinary start() method. In this mode however the signal, which fires once the process has finished, calles upon a slot which deletes the object itself: delete this;. It works. The process is running independently and we can set an environment.

So basically there is no need to use the detached start method. You can use the ordinary start method as long as your QProcess is an object on the heap. And if you care for memory leaks in this scenario you'd have to provide a similar mechanism as described above.

Best regards
D

Upvotes: 7

Related Questions