If available on your system pgrep
seems like a good fit here
pgrep -xf "systemctl stop Myservice"
pgrep
is provided by the same package as ps
(at least it is on the CentOS 7 system I referred to)
$ rpm -q --whatprovides $(which pgrep)
procps-ng-3.3.10-28.el7.x86_64
$ rpm -q --whatprovides $(which ps)
procps-ng-3.3.10-28.el7.x86_64
Even lightweight distros using BusyBox seem to be OK from a narrow test:
$ docker run --rm alpine pgrep --help
BusyBox v1.35.0 (2022-05-09 17:27:12 UTC) multi-call binary.
Usage: pgrep [-flanovx] [-s SID|-P PPID|PATTERN]
[...]
So I would think that if you have ps
you can rely on pgrep
, though things could be a bit less certain if your code ends up running inside a container (though this scenario seems pretty unlikely, given what you're attempting to do).
Are you trying to catch the systemctl stop ...
command in action? This seems like it would be quite prone to race conditions and/or performance issues. What if the C program loops too slowly and misses the command running, or too quickly and consumes excessive CPU?
If your goal is simply to detect when the service leaves active
state, this approach might be better:
systemctl status Myservice | grep -qE "^ +Active: active"
This should return a non zero exit code if the service is in anything other than active state.
As per your use case, it might be necessary to only flag when the state changes — rather than every time it sees non-active, via some additional logic.
pidof
takes multiple program names, so this looks for any process calledsystemctl
,stop
, orMyservice
. The obvious fix is to quote those three words as one string. However, that is probably not the process name: the program name issystemctl
, andstop
andMyservice
are its arguments. You may need a specificps -o pid,args | grep ...
to achieve this. – Paul_Pedant Jun 07 '22 at 15:49/dev/null
? That's never going to return anything. And why compare it to 0? 0 is a very unlikely output. If that's PHP you probably want to use the second argument tosystem
to get the return value. Otherwise you'll just get empty output in every case, which is never identical to 0. – frabjous Jun 07 '22 at 16:19system( )
call of whatever-language-that-is was coming back with the exit code of the executed command. If it does work in that manner, the approach seems valid, if not the command being run. If it doesn't work like that, well that is probably a discussion for a different Stack site. – bxm Jun 07 '22 at 16:24