Access thread information on Dragonfly BSD

On Dragonfly BSD, even it already provides pseudo proc file system, you can’t access thread information like Linux (/proc/$pid/task). You still need to use kvm:

......
kvm_t* kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
......
struct kinfo_proc *proc = kvm_getprocs(
                                kd,
                                KERN_PROC_PID | KERN_PROC_FLAG_LWP,
                                (int)(pid),
                                &cnt);
......
kvm_close(kd); 

According to man:

The number of processes found is returned in the reference parameter cnt. The processes are returned as a contiguous array of kinfo_proc structures.

There is kp_lwp member in kinfo_proc structure which records information of this thread, i.e., LWP. E.g., To print every thread’s ID:

......
printf("Process (%s) has %d threads, and LWP IDs are:\n", argv[1], cnt);
for (int i = 0; i < cnt; i++)
{
    printf("%d\n",  proc[i].kp_lwp.kl_tid);
}
......

For other BSDs, the principle may be similar.

P.S., the full code is here.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.