0

I'm trying to call a shell script from a Qt GUI, but after running the script, the bash session stays open when it should finish.

Having this code:

QString s = "./script.sh " + argument;
qint64 *pid = NULL;
QProcess process;
process.startDetached("/bin/bash", QStringList() << "-c" << s, NULL, pid);
bool finished = process.waitForFinished(-1);
std::cout << "ended";

So after running the script, it is expecting a command to be entered, I can put any command and it will execute it. The problem is that it never finishes until I enter a command.

I also tried modifying the s variable like this:

QString s = "./script.sh " + argument + " ;exit";

hoping that it would end up the bash session, but nothing happens.

If instead of using the function startDetached I use start it does close the bash session without the ;exit command.

Hope someone knows how to solve it or a workaround!

lpares12
  • 3,504
  • 4
  • 24
  • 45
  • What's the script and the argument? Alternatively, can you reproduce this with a standard command, such as `bash -c "echo done"`? – Toby Speight Jul 21 '16 at 16:49
  • A standrad command will reproduce the behaviour I want. The script has 2 commands and then a `exit 0` to end the script. The commands are executed correctly. – lpares12 Jul 22 '16 at 06:15

1 Answers1

2

startDetached() is a static method; you started a new process, but it's not represented by the process object.

When you wait for process to finish, it will wait forever, because process was never started.

Try something like:

process.start("/bin/bash", QStringList() << "-c" << s);
bool finished = process.waitForFinished(-1);

You might want to redirect I/O before start().

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • Also, the whole point of `startDetached` is to start and detach the process from current process, so waiting for it makes no sense really. – hyde Jul 21 '16 at 17:44
  • Yes, hyde that was not my question. That line is there for testing purposes. My question is how can I do for the child process to end, since it gets stuck in a bash session. Also tried the start() method but I need it non-blocking. – lpares12 Jul 22 '16 at 06:16
  • @deuseux, I don't fully understand what you're trying to do: `start()` doesn't block; `startDetached()` creates a non-child (therefore non-waitable) process. – Toby Speight Jul 22 '16 at 07:54
  • @TobySpeight, so if everything was right after executing `startDetached`, there is no worry to execute it again and again... we don't need to end the process? – Sigur Jul 15 '18 at 18:34