问题描述
我想获得其他进程的argv的如ps。
I want to get other process' argv like ps.
我使用的是Mac OS X 10.4.11上Intel或PowerPC运行。
I'm using Mac OS X 10.4.11 running on Intel or PowerPC.
首先,我读了PS和人的KVM code,然后我写了一些C code。
First, I read code of ps and man kvm, then I wrote some C code.
#include <kvm.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <paths.h>
int
main(void) {
char errbuf[1024];
kvm_t *kd = kvm_openfiles(_PATH_DEVNULL, NULL, _PATH_DEVNULL, O_RDONLY, errbuf);
int num_procs;
if (!kd) { fprintf(stderr, "kvm_openfiles failed : %s\n", errbuf); return 0; }
struct kinfo_proc *proc_table = kvm_getprocs(kd, KERN_PROC_ALL, 0, &num_procs);
for (int i = 0; i < num_procs; i++) {
struct kinfo_proc *pproc = &proc_table[i];
char **proc_argv = kvm_getargv(kd, pproc, 0);
printf("%p\n", proc_argv);
}
kvm_close(kd);
return 0;
}
在PowerPC上运行, kvm_getargv()
总是返回NULL。当跑
英特尔, kvm_openfiles()
失败,出现错误的/ dev / MEM:没有这样的文件
。
或目录
When ran on PowerPC, kvm_getargv()
always returned NULL. When ranon Intel, kvm_openfiles()
failed with error /dev/mem: No such fileor directory
.
五言中,我知道的权限。
Of cource, I know about permission.
第二,我试过的sysctl。
Second, I tried sysctl.
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#define pid_of(pproc) pproc->kp_proc.p_pid
int
main(void) {
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
int buffer_size;
sysctl(mib, 4, NULL, &buffer_size, NULL, 0);
struct kinfo_proc *result = malloc(buffer_size);
sysctl(mib, 4, result, &buffer_size, NULL, 0);
int num_procs = buffer_size / sizeof(struct kinfo_proc);
for (int i = 0; i < num_procs; i++) {
struct kinfo_proc *pproc = result + i;
int mib[3] = { CTL_KERN, KERN_PROCARGS, pid_of(pproc) }; // KERN_PROC_ARGS is not defined
char *proc_argv;
int argv_len;
sysctl(mib, 3, NULL, &argv_len, NULL, 0);
proc_argv = malloc(sizeof(char) * argv_len);
sysctl(mib, 3, proc_argv, &argv_len, NULL, 0);
fwrite(proc_argv, sizeof(char), argv_len, stdout);
printf("\n");
free(proc_argv);
}
return 0;
}
通过FWRITE,我得到的argv [0] argv的,但[1 ..]不是(环境变量
被打印出来。)
By fwrite, I got argv[0] but argv[1..] are not (environment variablesare printed out.)
有没有更多的办法做到这一点?
There is no more way to do it?
推荐答案
在10.6,KERN_PROCARGS2可用:
In 10.6, KERN_PROCARGS2 is available: https://gist.github.com/770696
此方式从PS使用,对MACFUSE PROCFS等。
This way is used from ps, procfs on MacFUSE, etc.
这篇关于获取使用C在OS X中的其他进程的argv的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!