Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if process is paused (with SIGSTOP) on OS X with C

Tags:

c

macos

signals

Given a process' pid, how can I determine if the process is paused (with SIGSTOP) or running?

I'm using OS X, so I don't have a /proc directory.

like image 497
Tyilo Avatar asked Oct 04 '22 21:10

Tyilo


1 Answers

This is how you do it:

#include <stdio.h>
#include <sys/sysctl.h>
#include <stdlib.h>
#include <string.h>

#define IS_RUNNING(proc) ((proc->kp_proc.p_stat & SRUN) != 0)

#define ERROR_CHECK(fun) \
    do { \
        if(fun) { \
            goto ERROR; \
        }\
    } while(0)

struct kinfo_proc *proc_info_for_pid(pid_t pid) {
    struct kinfo_proc *list = NULL;

    int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
    size_t size = 0;

    ERROR_CHECK(sysctl(mib, sizeof(mib) / sizeof(*mib), NULL, &size, NULL, 0));

    list = malloc(size);
    ERROR_CHECK(sysctl(mib, sizeof(mib) / sizeof(*mib), list, &size, NULL, 0));

    return list;

ERROR:
    if(list) {
        free(list);
    }
    return NULL;
}

int main() {
    pid_t pid = 1000;
    struct kinfo_proc *proc_info = proc_info_for_pid(pid);
    if(proc_info) {
        printf("Is running: %d\n", IS_RUNNING(proc_info));
    } else {
        printf("Could not stat process!");
        return 1;
    }
    return 0;
}
like image 172
Tyilo Avatar answered Oct 13 '22 01:10

Tyilo