Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: wait for xdg-open to quit before continuing

I have a Perl script that produces a pdf $pdffile in a temporary directory $tempdir and opens it using xdg-open. The script should then delete the working directory once the user is done looking at the file. Here's the part of the code that I'm having trouble with:

system "xdg-open $pdffile";
remove_tree($tempdir);

My understanding of system is that it should wait until the command returns before continuing the program. However, when I execute this code, I get a message "Could not open /tmp/diff14969/diffs.pdf". If I replace xdg-open with okular (which is my system default) in the system command, it works as I want it to. (Similarly, it works if I hardcode any pdf viewer that lives on my system, but I don't want to do that for portability reasons.)

My guess is that xdg-open is starting the viewer in a new process and that the system command only waits for xdg-open to finish. Once xdg-open returns successfully, the script removes the temp directory before the viewer can open the file. How can I make the script wait for the actual viewer to finish instead?

like image 245
MTS Avatar asked Oct 13 '17 19:10

MTS


1 Answers

xdg-open uses different ways to open files depending on the desktop environment you are using. It doesn't actually "start the viewer" but asks (at least in Gnome) the desktop environment to open your file (for example using gio in Gnome that in turn uses dbus).

Therefore there is no simple way to know the PID of the viewer to wait for it to be exited, except by doing some non portable trickery.

A solution could be to use the module File::Temp (included in the perl distribution) and create your temporary file / directory with the UNLINK / CLEANUP flag that makes it being deleted when the variable holding the object goes out of scope (thus calling the DESTROY method). This way, as long as your script runs (and the variable doesn't go out of scope) the temporary file is accessible in the filesystem.

like image 68
Mid' Avatar answered Oct 20 '22 10:10

Mid'