FreeBSD KVM (Kernel Virtual Memory Access)

svnweb.freebsd.org/base/release/10.2.0/bin/pkill/
Tracker, is a filesystem indexer, metadata storage system and search tool.
fossies.org/linux/tracker/src/tracker/tracker-process.c

How can a process inquire, when it was started?
github.com/dnabre/misc/tree/master/proc_info, Get time process started
github.com/hishamhm/htop/blob/master/freebsd/FreeBSDProcessList.c

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

#include <signal.h>

/* _POSIX2_LINE_MAX */
#include <limits.h>

/* kvm_openfiles(), kvm_getprocs() */
#include <kvm.h>

/* errx() */
#include <err.h>

/* _PATH_DEVNULL */
#include <paths.h>

/* O_RDONLY */
#include <fcntl.h>

/* KERN_PROC_PROC */
#include <sys/sysctl.h>

/* struct kinfo_proc */
#include <sys/user.h>

#define STATUS_MATCH    0
#define STATUS_NOMATCH  1
#define STATUS_BADUSAGE 2
#define STATUS_ERROR    3

int
main(int argc, char **argv)
{
    int i;

    /* PID */
    pid_t mypid;
    pid_t pid;

    /* KVM openfiles() */
    kvm_t      *kd;
    const char *execf;
    const char *coref;
    char        buf[_POSIX2_LINE_MAX];

    /* KVM getprocs() */
    int                 nproc;
    struct kinfo_proc  *plist;
    struct kinfo_proc  *kp;

    /* KVM getargv() */
    char **strv;

    char *selected;

    execf = NULL;
    coref = _PATH_DEVNULL;

    mypid = getpid();

    /*
     * Retrieve the list of running processes from the kernel.
     */
    kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
    if (kd == NULL)
        errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);

    /*
     * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
     * just want processes and not individual kernel threads.
     */
    plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
    if (plist == NULL) {
        errx(STATUS_ERROR, "Cannot get process list (%s)",
            kvm_geterr(kd));
    }
    printf("nproc=%d\n", nproc);

    /*
     * Allocate memory which will be used to keep track of the
     * selection.
     */
    if ((selected = malloc(nproc)) == NULL) {
        err(STATUS_ERROR, "Cannot allocate memory for %d processes",
            nproc);
    }
    memset(selected, 0, nproc);

    /*
     * Take the appropriate action for each matched process, if any.
     */
    for (i = 0, kp = plist; i < nproc; i++, kp++) {
        printf("comm=%s tdname=%s wmesg=%s login=%s lockname=%s emul=%s loginclass=%s",
            kp->ki_comm,
            kp->ki_tdname,
            kp->ki_wmesg,
            kp->ki_login,
            kp->ki_lockname,
            kp->ki_emul,
            kp->ki_loginclass);
        if ((strv = kvm_getargv(kd, kp, 0)) != NULL) {
            printf(" argv=%s", strv[0]);
        }
        printf("\n");
    }

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *