Question

I have to read a script from the user and call a QProcess passing that script as a file.

For example, the user insert this, say, Python script

import sys
print(sys.copyright)

and I have to put that script in a file, and call the python interpreter using that file.

I thought to use a QTemporaryFile, because that file will serve just when launching the process, and I have no need to keep it open.

The question is: is it safe to open a QTemporaryFile, write something in it, pass that file to a process (which will continue indefinitely) and then destroy the temporary file? What if the process will need that file again? What if the process keep the file open?

I reckon that, if kept open by the process, no problem will arise: probably the QTemporaryFile will unlink the path, but data will still be accessible in memory.

But what if the process will try to open the file again?

Here a snippet as example (wrote on the fly)

QString script = QInputDialog::getText(blah);
QTemporaryFile tmp;
if (tmp.open()) {
    tmp.write(script.toUtf8());
    QStringList params;
    params << tmp.fileName();
    QProcess *proc = new QProcess("/usr/bin/python3");
    proc->start(params);
}
Was it helpful?

Solution

As I understand it, in the case of the 'autoRemove' flag (which is on by default), the QTemporaryFile will exist so long as the instance of QTemporaryFile exists. Therefore, in the code you originally presented, when tmp goes out of scope, the file will be removed. Calling open / close on the object will not delete the file.

You could dynamically allocate the file with QTemporaryFile* pTmp = new QTemporaryFile and then delete it later, if you know when the python script has finished with it.

OTHER TIPS

Ouch, I just noted the autoRemove flag in the QTemporaryFile. I guess this could be a solution: if set to false, the file will not be removed from the disk, so the process is free to reuse the file - I think.

Temporary files should be stored in system's default location, so I guess that the files are not removed until a reboot (at least, I believe Linux works this way).

This is just an idea, but I will wait for other answers or confirmations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top