in reply to Re: Perl Script own path
in thread Perl Script own path

On some Unix-systems (Linux among them) you can actually assign to $0 to change the way the process shows up in the process list (I've seen that done e.g. to prevent passwords that are supplied on the commandline to show up with ps).

I now wonder if you changed your $0 to something else - would there be any way to recover the true script-path again?

Replies are listed 'Best First'.
Re^3: Perl Script own path
by Marshall (Canon) on Jul 25, 2011 at 05:21 UTC
    I was quite astonished! I put an $0 = 'xyzzy"; statement in my Perl code and I'll be, ps -ef shows xyzzy in the process table! I am shocked and don't know why this could happen! I would have never thought that $0 was a writable variable. My brain was thinking along the lines of C and its char** argv, which is normally used as "read only", but that's not what is happening here.

    I guess you could save: my $saved = $0; or make a { local $0; $0 = 'xyzzy'; other stuff}, but I'm not sure why that would be useful?

      My brain was thinking along the lines of C and its char** argv, which is normally used as "read only"

      argv[0] isn't read-only in C, either:

      /tmp>cat foo.c #include <string.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char ** argv) { pid_t pid; int status; strcpy(argv[0],"Did you expect this?"); pid=fork(); if (pid<0) { perror("Can't fork"); } if (pid==0) { execlp("ps","ps","-f",NULL); exit(127); } else { waitpid(pid,&status,0); } exit(0); } /tmp>make foo cc foo.c -o foo /tmp>./foo UID PID PPID C STIME TTY TIME CMD foken 1255 1254 0 15:06 pts/0 00:00:00 -bash foken 1676 1255 0 15:21 pts/0 00:00:00 Did you expect this? foken 1677 1676 0 15:21 pts/0 00:00:00 ps -f /tmp>

      Of course, manipulating argv[] is not portable. Most Unixes support it in a more or less limited way. The example from above runs on linux 2.6.29.6, and exibits the typical Linux behavior. BSDs and other Unixes may show a different behaviour. On Windows, such a program would only manipulate a copy of the original command line, generated by the C runtime library. (Windows has no concepts like fork(), exec(), or argc/argv[]. Windows programs are expected to parse a single string containing all arguments.)

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)