Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: exec sometimes changes pid

by moritz (Cardinal)
on Aug 02, 2009 at 22:16 UTC ( [id://785292]=note: print w/replies, xml ) Need Help??


in reply to exec sometimes changes pid

It might related to the fact that you don't pass a simple command to exec, but rather a string with shell meta characters.

So when you call exec it overrides the current (child) program with the shell from /bin/sh which interprets the string for you, which in turns starts another perl script which prints a PID (which is not the same as the one you forked off originally).

Maybe your other system is smart enough to detect that it doesn't really need to spawn a shell, but can execvp directly the new perl process. I'd guess that you'll get the same result on both systems if you use the LIST form of exec instead.

Replies are listed 'Best First'.
Re^2: exec sometimes changes pid
by doom (Deacon) on Aug 03, 2009 at 00:34 UTC

    Some preliminary trials show you're probably right (though I still don't see what could be different on these two systems... maybe a different version of some IPC::* module?). In any case, I was experimenting with the list form of exec for other reasons, and I finally made it through the gotchas:

    my @cmd = ('perl', '-e print "child: id after exec: $$\n"; print "child: sees processes...\n " , grep { m/perl/ } `ps ax` , "\n"; ', ); print "parent: pre-fork id $$\n"; if ( my $pid = fork ) { # this is parent code print "parent: post-fork id $$\n"; print "parent: return from fork is: $pid\n"; sleep 3; print "parent: still here, with id $$\n"; print "parent: sees processes...\n " , grep { m/perl/ } `ps ax` , "\n"; } else { # this is child code die "cannot fork: $!" unless defined $pid; print "child believes it is: $$\n"; exec {$cmd[0]} @cmd; }

    The gotchas:

    • You use the command name first ("indirect object" syntax, ala printing to a file handle), *and* have the command name again inside the list. The second one is what appears in the process listing, the first is the program that's actually run.
    • From the shell, you typically do a perl -e 'some code', but if you're going around the shell, those single quotes on the string fed to "-e" just get in the way: @cmd = ('perl', q{-e some code }).

Log In?
Username:
Password:

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

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

    No recent polls found