Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Multiple asynchronous QProcesses



  • I'm trying to run multiple QProcess at runtime (around 1-12) aynchronously so I create a vector of unique_ptr for each QProcess and connect them in a loop like this:

    std::vector<std::unique_ptr<QProcess>> processes;
    processes.resize(threads);
    for (int i=0; i<threads; i++)
    {
        processes[i] = std::make_unique<QProcess>();
    }
    ...
    for (int i=0; i<threads; i++)
    {
    	connect(processes[i].get(), &QProcess::readyReadStandardOutput, this, [&]()
    	{
    		QByteArray readStdOut = processes[i]->readAllStandardOutput();
    	});
    }
    

    However when I actually start my processes and receive data, I always get a segmentation fault because the index i is always equal to threads when data is received. Why does this happen and how do I fix this?

    Thanks


  • Lifetime Qt Champion

    Hi
    You capture i by reference so it will always point to the last values and not the value it had at that moment.

    
    Try
    ....[&processes, i ](){};
    or
    ....[&, i ](){};
    

    so we capture process by ref and then i by value.



  • Thanks :)


Log in to reply