16

I have a script i want to run 2 programs at the same time, One is a c program and the other is cpulimit, I want to start the C program in the background first with "&" and then get the PID of the C program and hand it to cpulimit which will also run in the background with "&".

I tried doing this below and it just starts the first program and never starts cpulimit.

Also i am running this as a startup script as root using systemd in arch linux.

#!/bin/bash

/myprogram &

PID=$!

cpulimit -z -p $PID -l 75 &

exit 0
Skilo Skilo
  • 526
  • 4
  • 11
  • 23
  • `sleep 30 & PID=$! sleep $PID & ps -f` Works fine for me. – Raul Andres Feb 03 '14 at 16:24
  • Am i correct to assume that $! is the id of the last executed command and by using the variable PID am i able to access that value? – Skilo Skilo Feb 03 '14 at 16:29
  • Yes, it is, in my code output (linebreaks are missing) there are two forked process. First one is sleep 30 and second one sleep 17568, that matches the pid of the firt sleep. Maybe your myprogram is a shell that forks another process? – Raul Andres Feb 03 '14 at 16:32
  • 3
    You might want to choose a different variable name. `MY_PID=$!` – Elliott Frisch Feb 03 '14 at 16:33
  • 1
    What does `cpulimit` do? It sounds like something that completes fairly quickly, so it probably runs in the background and exits before you can check for it after the start-up script completes. – chepner Feb 03 '14 at 16:35
  • @chepner cpulimit limits the percentage of cpu resources of a specified program, the -z option makes cpulimit exit if no suitable process if found the -p option is for a PID, and the -l option is the percentage of cpu resources to allow, It also takes a -e argument which can be the path of the program but for some reason that option never worked for me, However the -p option works fine from the command line. – Skilo Skilo Feb 03 '14 at 16:42
  • OK; what makes you think that it isn't running, though? – chepner Feb 03 '14 at 17:24
  • If you're launching this from systemd, why not just use [systemd's LimitCPU feature?](https://www.freedesktop.org/software/systemd/man/systemd.exec.html) – Kevin M Granger Mar 22 '16 at 18:18

2 Answers2

5

I think i have this solved now, According to this here: link I need to wrap the commands like this (command) to create a sub shell.

#!/bin/bash

(mygprgram &)
mypid=$!
(cpulimit -z -p $mypid -l 75 &)

exit 0
Community
  • 1
  • 1
Skilo Skilo
  • 526
  • 4
  • 11
  • 23
2

I just found this while googling and wanted to add something.

While your solution seems to be working (see comments about subshells), in this case you don't need to get the pid at all. Just run the command like this:

cpulimit -z -l 75 myprogram &
chris137
  • 189
  • 1
  • 11