为什么 sysctl 在 Mac OS X 上产生 E_INVAL?
下面是一个精简的(省略了错误/空检查)C/Obj-C 代码片段,它使用 sysctl 获取 PID 50 的特定进程的 argv。
...
int getProcessArgs[3] = { CTL_KERN, KERN_PROCARGS, 50 };
sysctl(getProcessArgs, 3, NULL, &length, NULL, 0);
char* processArgs = malloc(length * sizeof(char));
sysctl(getProcessArgs, 3, processArgs, &length, NULL, 0);
...
第一次调用 sysctl(以确定 argv 字符串的大小)数组)成功。返回的长度约为 1600,比我预期的要大,但我认为并非不合理。 Malloc 成功。第二次调用 sysctl 返回 -1,将 errno 设置为 22,E_INVAL。
我查看了其他代码,包括 这个问题< /a>,但看不到我的问题。我缺少什么?
Below is a pared-down (error/null checks omitted) snippet of C/Obj-C code that uses sysctl to get the argv of a particular process with PID 50.
...
int getProcessArgs[3] = { CTL_KERN, KERN_PROCARGS, 50 };
sysctl(getProcessArgs, 3, NULL, &length, NULL, 0);
char* processArgs = malloc(length * sizeof(char));
sysctl(getProcessArgs, 3, processArgs, &length, NULL, 0);
...
The first call to sysctl (to determine the size of the argv string array) succeeds. The returned length is ~1600, larger than I would expect, but I suppose not unreasonable. Malloc succeeds. The second call to sysctl returns -1, setting errno to 22, E_INVAL.
I've looked at other code, including that from this question, but can't see the problem with mine. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我尝试将您的代码包装到一个程序中,它工作正常,并在查询我自己的进程之一时打印出其他进程的 argv 等,即与调用进程具有相同 uid 的进程 <代码>sysctl()。
“比我预期的要大”是因为返回了进程的环境变量以及命令行参数。 (所有这些信息的格式是什么并不明显。)
当查询不同用户的进程时,我从第二个
sysctl
中得到了与您相同的 EINVAL看到。我想这被认为是对其他人进程的不合理好奇,但您会认为第一个 sysctl 也会失败。(当查询不存在的 pid 时,第一个 sysctl 会失败并显示 EINVAL。)
这一切似乎都没有大量记录:在 Leopard 上,KERN_PROCARGS 甚至没有出现在
sysctl
手册页。I tried wrapping your code up into a program, and it works fine and prints out the other process's argv etc when inquiring about one of my own processes, i.e., one with the same uid as the process invoking
sysctl()
.The "larger than I would expect" aspect is because the process's environment variables are returned as well as the command line arguments. (It's not obvious what the format of all this information is.)
When inquiring about a different user's process, I get the same EINVAL from the second
sysctl
that you've been seeing. I guess this is considered unreasonable curiosity about other people's processes, but you'd think the firstsysctl
would fail too.(When inquiring about a non-existent pid, the first
sysctl
fails with EINVAL.)This all seems to be massively underdocumented: on Leopard,
KERN_PROCARGS
doesn't even appear in thesysctl
man page.