3

I was trying to get pid of process I ran with setsid and which ought to run in background like this:

test.sh:

#/bin/bash
setsid nohup ./my_program &
echo $!

if I run ./test.sh it will print a pid of my_program process and it's exactly what I need. But if run this commands one by one in my shell like this:

$ setsid nohup ./my_program &
$ echo $!

It will give me a pid of setsid command (or may be something else, but it almost all times gives me pid of my_program minus one).

What is happening here? Why results of commands I ran in terminal by myself differs from results of test.sh script?

Btw, may be you know some easy way of process which I started with setsid and which I need to run in background?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
PepeHands
  • 1,368
  • 5
  • 20
  • 36
  • Maybe it has to do with setsid's forking behavior? It only forks if it is the process group leader; see [here](http://stackoverflow.com/a/9685973/1735215). – 0range Apr 22 '16 at 14:31
  • To get the pid of a process executed via setsid, you may try [this](http://stackoverflow.com/a/19767312/1735215) – 0range Apr 22 '16 at 14:57
  • @0range yeah, I think first link is exactly what I needed. Thanks a lot! Could you please write this as an answer so I can accept it? – PepeHands Apr 22 '16 at 17:00
  • Please try to come up with a title specific enough that folks can know what your question is about (thus, if they're having their own problem with $!, whether answers to your question are also applicable and useful to them) without needing to click through and read it; I've tried to edit it to do that here. – Charles Duffy Apr 22 '16 at 22:59

2 Answers2

1

Repost of comments above as an answer:

This is because setsid only forks the current process if it is the process group leader. A detailed explanation can be found here.

To get the pid of a process executed via setsid, the approaches given here may be tried.

Community
  • 1
  • 1
0range
  • 2,088
  • 1
  • 24
  • 32
1

setsid will call fork to ensure that it creates a new process group aswell as a new session, hence the resulting pid will not match the pid of setsid. The most clean work-around would be that my_program stores its pid into a file.

When you later want to send kill to my_program, you should check that the pid actually matches a program named my_program via /proc file system or calling the ps command with some magic code around it. (This is a very common method used by many daemons)

Stian Skjelstad
  • 2,277
  • 1
  • 9
  • 19