2

I am doing some experiments to know how environment variables are inherited from parent process to child process by executing shell scripts in zsh and then use pstree <username> to see the inheritance tree.

I suppose that zsh do a fork to run a script. But the process name in the pstree is the script file name not zsh.

#parent.sh
#! /bin/zsh
export AMA=1
./childEcho.sh #call child

#childEcho.sh
#! /bin/zsh
echo ${AMA}
./subchild.sh #call sub_child

#subchild.sh
#! /bin/zsh
echo ${AMA}
sleep 5d #sleep so that pstree can see the process tree 

Then pstree shows that

sshd───zsh───parent.sh───childEcho.sh───subchild.sh───sleep

Then I delete the hashbang header in the scripts, run again and then by pstree, I will get

sshd───zsh───sh───sh───sh───sleep

So the process is now sh instead of the script file name.

  1. Why we have this different behavior?
  2. How pstree determines the process name and draws the tree?
  3. Something changed the process name at runtime?
4

A program can change it's own command line (as shown in ps's CMD column, or pstree). That's what zsh is doing—it's changing its command name to the shell script, presumably to make it easier to tell what each zsh is doing when looking at ps.

For example (though I'm using bash, not zsh, but the same works in zsh—I tested):

$ perl -E '$0 = "I AM PERL"; sleep(60);' &
[1] 504
$ ps 504
  PID TTY      STAT   TIME COMMAND
  504 pts/22   S      0:00 I AM PERL

You can get the actual executable by readlink /proc/PID/exe, at least on Linux.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.