From an app written in C++, how can I tell that my launch daemon is currently running? And preferably how to get its PID?
For instance, if I run the following in the terminal:
launchctl list com.example.MyService
I get a JSON output, where it gives me the PID of the daemon process.
Having studied the source code for launchctl, I came up with the following:
const char *label = "com.example.MyService";
launch_data_t msg = launch_data_alloc(LAUNCH_DATA_DICTIONARY);
launch_data_dict_insert(msg, launch_data_new_string(label), LAUNCH_KEY_GETJOB);
launch_data_t resp = launch_msg(msg);
launch_data_free(msg);
if(resp != NULL)
{
launch_data_type_t tt = launch_data_get_type(resp);
if(tt == LAUNCH_DATA_DICTIONARY)
{
launch_data_t pid_data =
launch_data_dict_lookup(resp, LAUNCH_JOBKEY_PID);
if (pid_data)
{
if (launch_data_get_type(pid_data) == LAUNCH_DATA_INTEGER)
{
pid_t pid = launch_data_get_integer(pid_data);
//...
}
}
}
else if(tt == LAUNCH_DATA_ERRNO)
{
int nErr = launch_data_get_errno(resp);
//ESRCH = 3 = No such process
}
launch_data_free(resp);
}
else
{
//No such
}
But when I run the code above for my launch daemon "label", I get my launch_data_type_t
returned as LAUNCH_DATA_ERRNO
and launch_data_get_errno
returns ESRCH
(like I showed above.)
What am I doing wrong?