c - task_for_pid 总是在 C 中的 darwin 上返回 (os/kern) 失败

标签 c ios darwin mach-o

由于某些原因,我无法从 task_for_pid() 中得到任何结果 我找不到太多信息,但我正在尝试将其附加到另一个进程并搜索其内存,但每次我尝试使用 task_for_pid 时,我都会遇到相同的 (os/kern) 失败错误。

#include <stdio.h>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>

int main(int argc, char* argv[])
{
mach_port_name_t task;
printf("%d\n", argv[1]);
int pid = atoi(argv[1]);
printf("%d\n%d\n", pid, current_task());
int error = task_for_pid(2055, 24269, &task);
printf("%x\n", task);
if (error)
{
printf("task_for_pid return error:\n %s\n", mach_error_string(error));
} else {
printf("Get the process %d's task port : %x\n", pid, task);
}
return 0;
}

输出如下:

gcc -o test test.c;./test 24269
803206115
24269
2055
0
task_for_pid return error:
 (os/kern) failure

知道为什么我从来没有接到过任务吗? 我以 root 身份运行它。

正如 Adam Rosenfield 所说,它确实在 header 中表示它已过时,但如果那是真的,我是否仍可以使用旧版本的工具链编译和运行它?或者它被什么取代了?有谁知道吗?

最佳答案

  1. 您确定您正在以 root 身份运行吗?
  2. 您确定进程 24269 仍在运行吗?

我在 Mac OS X 10.6.8 上使用任何正在运行的进程运行此代码(使用 sudo)都没有问题:

#include <stdio.h>
#include <stdlib.h>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>

int main(int argc, char* argv[])
{
    task_t task;
    pid_t pid = argc >= 2 ? atoi(argv[1]) : 1;
    kern_return_t error = task_for_pid(current_task(), pid, &task);
    printf("%d -> %x [%d - %s]\n", pid, task, error, mach_error_string(error));
    return error;
}

例如,这是我的 pid 182 (Dock) 结果

$ sudo ./task_for_pid 182
182 -> 413 [0 - (os/kern) successful]

关于c - task_for_pid 总是在 C 中的 darwin 上返回 (os/kern) 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6659527/

相关文章:

c - 在不使用第 3 方库的情况下基于 C 中的 char* 的多平台 Unicode 处理?

ios - iPhone 5S 特定错误 : No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=arm64, VALID_ARCHS=armv7 armv7s)

macos - OSX 上的 PF header net/pfvar.h 丢失

xcode - 添加自定义 macosx.internal SDK

ios - 我可以找到创建命名 OSMallocTag 的库吗?

c - valgrind - 大小为 1 的无效读取地址 0x0 在 execlp 期间未进行堆栈、分配或(最近)释放

c - 字符串文字 : Where do they go?

c++ - C++ 中 ## 运算符的用途是什么,它叫什么?

ios - Swift:如何从字典中删除空值?

ios - 如何消除类 'STEDataSheet' 的重复接口(interface)定义