7

My Makefile look something like this:

setsid ./CppServer>daemon.log 2>&1 &
echo $!>daemon.pid

What I expect it to do is to store the PID of my_awesome_script in corresponding file. However there's nothing there. So where's the problem?

Alex Bochkarev
  • 2,851
  • 1
  • 18
  • 32

2 Answers2

4

If your makefile really looks like this you will get an error, because I don't see any actual make syntax, just shell syntax. However, my crystal ball tells me that these two lines might be part of the recipe for a rule. If they are, you should realise how make executes recipes; for each line a separate subshell is created, in which that line's command is executed independently: your two commands don't know anything about each other's environment. If you want two commands to be executed in the same subshell, you should issue them as one line (using line continuation characters if necessary), or use make's ONESHELL directive.

eriktous
  • 6,569
  • 2
  • 25
  • 35
  • 2
    That's not helpful. Tell me: why is $! empty when asked in Makefiles? – nalply Aug 08 '11 at 08:46
  • 2
    @nalply: It's empty because make doesn't define a variable with that name. If you want to use it in the shell you have to escape the dollar sign: `$$!`, but you have to be aware of my remark about issuing the commands on one line, separated by e.g. a semicolon. – eriktous Aug 08 '11 at 23:12
  • @eriktous great answer, definitely helpful. I did have nalply's issue next, of course the $$! solves that. – David Oct 18 '13 at 15:25
0

The variable you're trying to use prints the pid of the last program run in the background. It is correctly written as echo $! > filename.extension. But since you are running it in the foregorund you have two choices. Run it in the background by appending an & to the end of the line ./script_to_run &, or you can have the script itself print to file the pid of the currently running process by using echo $$ > filename.extension (inside the script). Here is a link that might help you http://tldp.org/LDP/abs/html/internalvariables.html

rubixibuc
  • 7,111
  • 18
  • 59
  • 98