Get PPid from specific pid in C

Viewed 64

I want to find a way to get the ppid of a specific pid only using C low-level function. I know there is a way with bash commands, like "ps" etc, but I want to do it only in C language.

1 Answers

This should work as you expect. I used pid = 373 which is my current /usr/sbin/cron. It properly reports PPID of 1 (init):

% ./getppid
PPid = 1

Sample code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXBUF      (BUFSIZ * 2)

int main () {
    int ppid, pid = 373;  // my current cron pid
    char buf[MAXBUF];
    char procname[32];  // Holds /proc/4294967296/status\0
    FILE *fp;

    snprintf(procname, sizeof(procname), "/proc/%u/status", pid);
    fp = fopen(procname, "r");
    if (fp != NULL) {
        size_t ret = fread(buf, sizeof(char), MAXBUF-1, fp);
        if (!ret) {
            perror("Error reading file: ");
            exit(1);
        } else {
            buf[ret++] = '\0';  // Terminate it.
        }
    }
    fclose(fp);
    char *ppid_loc = strstr(buf, "\nPPid:");
    if (ppid_loc) {
        ppid = sscanf(ppid_loc, "\nPPid:%d", &ppid);
        if (!ppid || ppid == EOF) {
            perror("scanf:");
            exit(1);
        }
        printf("PPid = %d\n", ppid);
    } else {
        printf("Error finding PPid: in status\n");
        exit(1);
    }
}
Related