0

Using /usr/bin/osascript JS to automate my task, struggling with a check if process is already running or not:

const app = Application.currentApplication()
app.includeStandardAdditions = true

function run(args) {
  const query = args[0]
  let response = 'Wrong command passed'
  if (query === 'on') { // need to check if process named "asdf" is already running
    response = 'Process turned ON'
  } else if (query === 'off') { // need to check if process named "asdf" is already running
    response = 'Process turned OFF'
  }
  return response
}

JXA documentation could be better, i want to implement a check in an if construction. I've tried to make it using:

const se = Application('System Events')
const process = se.processes.byName('processname')

But it has no effect.

RobC
  • 22,977
  • 20
  • 73
  • 80
Alexander Kim
  • 17,304
  • 23
  • 100
  • 157

2 Answers2

2

Solved myself:

const PNAME = `ps aux | grep processname | grep -v grep | wc -l | xargs echo`

Getting "processname", if it's running, it returns 1, otherwise 0.

Were I to call out to a shell to do this, I would aim to make it as an efficient combination of commands as possible. xargs, wc, and the second pipe into grep are all unnecessary: if grep processname matches, the exit status of the command will be 0, and in all other cases, non-zero. It looks like the only reason you pipe through to those other programs is because you didn't utilise the most effective set of program options when calling ps:

const PNAME = 'ps -Acxo comm | grep processname > /dev/null; echo $(( 1 - $? ))'

Even this use of grep is unnecessary, as bash can pattern match for you:

const PNAME = '[[ "$( ps -Acxo comm )" =~ processname ]]; echo $(( 1 - $? ))'

But, putting that to one side, I wouldn't get a shell script to do this unless I were writing a shell script. JXA is very capable of enumerating processes:

sys = Application('com.apple.SystemEvents');

sys.processes.name();

Then, to determine whether a specific named process, e.g. TextEdit, is running:

sys.processes['TextEdit'].exists();

which will return true or false accordingly.

CJK
  • 5,732
  • 1
  • 8
  • 26
0

Solved myself:

const PNAME = `ps aux | grep processname | grep -v grep | wc -l | xargs echo`

Getting processname, if it's running, it returns 1, otherwise 0. All what's left to do is:

if (app.doShellScript(PNAME) < 1) {
  // do something
} else {
  // do something else
}
RobC
  • 22,977
  • 20
  • 73
  • 80
Alexander Kim
  • 17,304
  • 23
  • 100
  • 157