Alois Mahdal
Alois Mahdal

Reputation: 11243

Spawn Perl script as a process with particular name

I need a Perl script to spawn itself with an arbitrary name, i.e. so that the rest of OS will see it as e.g. "aaa.exe". I had impression that this is possible to do in Perl but now I'm not sure.

I'm using Strawberry Perl 5.14, 32-bit build, on Windows 7 amd64.

Here's what I tried and does not work:

#!perl -w
# spawnself.pl

if ($ARGV[0]) {
    my $name = ($ARGV[0]);
    system {"perl"} $name, $0;
} else {
    print "running as $^X, PID is $$\n";
    print "press Enter to quit...\n";
    my $trash = <>;
}

I composed this based on example from exec perldoc page (system page links there): exec {'/bin/csh'} '-sh';, where, IIUC, the goal is to make /bin/csh think it is "-sh", though I'm not sure if that is also supposed to make csh look like "-sh" from the outside. Plus, it's UNIX example, while I'm on Windows.

I'd like to have a script, which being run (from command line) as spawnself.pl aaa.exe would spawn itself, printing running as aaa.exe, PID is 1234, and looking into Task manager would show this program as "aaa.exe". However, my snippet as well as the rest of the world still sees itself as "perl.exe":

What am I doing wrong? Can somebody please shed some light on this?

Upvotes: 2

Views: 448

Answers (1)

Alois Mahdal
Alois Mahdal

Reputation: 11243

I found a quite ugly, though working, hack:

#!perl -w
#spawnself-ugly.pl

use File::Copy;

if ($ARGV[0]) {
    my $name = ($ARGV[0]);
    copy($^X, $name);
    my @args = ($name, $0);
    system @args;
} else {
    print "running as $^X, PID is $$\n";
    print "press Enter to quit...\n";
    my $trash = <>;
}

I actually make a copy of perl.exe and run that one, so finally I simply am running "aaa.exe", so there's no need to lie about anything.

Upvotes: 1

Related Questions