Search code examples
linuxbashpidbackground-task

PID of background task is different to the listed task PID using ps


I have a strange issue, I can't quite get my head around. What I do is run a function called fn_rundumper which basically just calls the bash code:

pterm -z "cmd.sh" param1 &

Here is the output of that, which includes the background pid "27938858":

fn_rundumper
running fn_dumper...
[1] 27938858
fn_dumper...done

Then I look at the job numbers that are running this also shows PID "27938858":

jobs -l
[1] + 27938858 Running              $(pterm -z "$SCRIPTS_DIR/run_dumper.sh" $VO

Then I do a ps command to see what pterms are running:

ps | grep pterm
 24285189 ?        00:00:00 pterm
 27938859 ?        00:00:00 pterm

This yields the PID 27938859. This is different to the others!

When I kill PID 27938858 nothing seems to happen. When I kill PID 27938859 then the background pterm is closed.

The problem is that I may want to run many different background pterms as well as some pterms that are not opened as background tasks (i.e. run separately). So when I come to tidy up I just want to close the pterms that I have opened via my script.

I was trying to use jobs -l to see the PIDs I need to close, but as I just described this is the wrong PID.

Can anyone explain why this happens? and also what I need to do to get the correct PID? Thanks!

- Edit1 -

The best I can think of is to do a ps | grep pterm before and after and compare the results to find the new pterm PID... do-able, but ugly :(

- Edit2 -

I tested this again on the command line (no function call):

First I did:

`pterm -z "$VOE_SCRIPTS_DIR/run_dumper.sh" $PROJECT_DIR` &

And then looked at the ps / $! results and got the same behavior.

Then I did:

pterm -z "$VOE_SCRIPTS_DIR/run_dumper.sh" $VOE_PROJECT_DIR &

i.e. removed the back-ticks, now the PIDs all match up! I think I can remove the back-ticks from my code, but I don't really understand what that is all about!


Solution

  • Using $() or backticks (command substitution) creates a subshell. So 27938858 is the PID of a subshell which in turn inkokes pterm with PID 27938859.

    Command substitution seems useless in your example, so you should just remove it.