Reputation: 32408
openproc
provides API for retrieving data from /proc
. But all examples I found read data about all processes. With PROC_FILLENV
it should allocate environment variables:
allocate
environ
part ofproc_t
and read information from/proc/#pid/environ
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <proc/readproc.h>
int main(){
PROCTAB* proc = openproc(PROC_FILLENV);
proc_t proc_info;
memset(&proc_info, 0, sizeof(proc_info));
while (readproc(proc, &proc_info) != NULL) {
printf("%s\n", *proc_info.environ);
}
closeproc(proc);
}
But it still reads information about all processes. How can I filter processes by PID?
Upvotes: 1
Views: 476
Reputation: 32408
PROC_PID
flag and list of PIDs are needed as 2nd argument:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <proc/readproc.h>
// compile with:
// gcc environ.c -lprocps -o bin/environ
int main(){
pid_t* pidList= NULL;
pidList = (pid_t*) malloc(sizeof(pid_t)*2 );
// lookup only processes whose pid is contained in pidlist
pidList[0] = 1234;
pidList[1] = 0; // the list is terminated with 0
PROCTAB* proc = openproc(PROC_PID | PROC_FILLENV, pidList);
proc_t proc_info;
memset(&proc_info, 0, sizeof(proc_info));
while (readproc(proc, &proc_info) != NULL) {
int i = 0;
//environ is an array of *char
while(proc_info.environ[i] != NULL) {
printf("%s\n", proc_info.environ[i++]);
}
}
closeproc(proc);
free(pidList);
}
Upvotes: 1