Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

How to re-execute self?

by Eyck (Priest)
on Jun 15, 2005 at 18:35 UTC ( [id://467008]=perlquestion: print w/replies, xml ) Need Help??

Eyck has asked for the wisdom of the Perl Monks concerning the following question:

I would like to clean the state of the script, close all filehandles etc, and I think the best way is to die(), but then, I would need external program to re-execute the script.

So I was thinking along the lines of:

system("perl -w script.pl"); die();

Howether, that would be problematic if there would be some resource that cannot be shared, and generally it would be better to have the script execute serially, and avoid the parallel execution of the same script.

To do that, I thought about something like that:

#!/usr/bin/perl sleep(10);
or even better:
#!/usr/bin/perl BEGIN { sleep(10); };

But it looks unclean and seems like it's not a very good solution.

How would correct solution look like?

update It seems that the correct solution is as suggested by tye:

exec( $^X, $0, @ARGV ) or die "Can't re-exec myself($^X,$0): $!\n";
it seems that besides loading new process image, it cleans up everything I can think of (fds, opened sockets)
Thanks.

UPDATE Howether, this doesn't work that well when you pack your scripts with PAR, then what you get is:

Unrecognized character \x7F at /home/eyck/script.exe Line 1

this is of course because script.exe is not a perl script, thus exec($0,@ARGV) should work in that case.

Replies are listed 'Best First'.
Re: How to re-execute self?
by Fletch (Bishop) on Jun 15, 2005 at 18:38 UTC

    If you use exec you'll "overwrite" the current instance of your script with a new invocation.

    exec( $0, @ARGV ) or die "Can't re-exec myself: $!\n";

    --
    We're looking for people in ATL

      exec( $^X, $0, @ARGV ) or die "Can't re-exec myself($^X,$0): $!\n";

      doesn't require that $0 be written such that the kernel knows that it is a Perl script and might prevent the kernel from picking a different version of Perl than was originally used.

      - tye        

Re: How to re-execute self?
by ikegami (Patriarch) on Jun 15, 2005 at 18:38 UTC
    If you look at documentation for system, you'll see it doesn't return until the command finishes executing. It's definitely not what you want. exec instead of system+die should do the trick nicely.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://467008]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-19 02:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found