http://qs321.pair.com?node_id=11111495

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

As the title says: on Linux, if you assign anything to $0 (with the intent to change the program's name as displayed by ps et al.), not just the the program's name and arguments are changed, but the environment (as shown in /proc/PID/environ) is cleared as well, or more precisely, filled with spaces.

The perlvar entry for $0 contains a paragraph that vaguely alludes to this:

            In some platforms there may be arbitrary amount of padding, for
            example space characters, after the modified name as shown by
            "ps". In some platforms this padding may extend all the way to
            the original length of the argument area, no matter what you do
            (this is the case for example with Linux 2.2).

So I kind of understand what happens here and why, I just find it rude.

It is somewhat more concerning that the effect persists even if you localize $0.

#!/usr/bin/perl sleep 10; { local $0 = 'changed'; sleep 10; } sleep 10;

When you run the program above, and watch a process list in a different terminal, you can observe that the apparent process name changes to 'changed' after 10 seconds, then changed back again, but if you watch the contents of /proc/PID/environ at the same time, you can see that it gets filled with spaces, then doesn't change back.

Two additional things to note:

I think that an argument could be made that Perl should try to preserve the contents of /proc/PID/environ when changing $0, and do a more thorough job of restoring the original command line if $0 is localized.