开发者

task_for_pid always returns (os/kern) failure on darwin in C

开发者 https://www.devze.com 2023-03-19 08:13 出处:网络
For some reasons I cannot get anything to come out of task_for_pid() I can\'t find very much information but what I am tryi开发者_StackOverflow中文版ng to do it attach to another process and search it

For some reasons I cannot get anything to come out of task_for_pid() I can't find very much information but what I am tryi开发者_StackOverflow中文版ng to do it attach to another process and search its memory, but every time I try to use task_for_pid, I get the same (os/kern) failure error.

#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;
}

Output looks like:

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

Any idea's as to why im not getting a task, ever? I am running it as root.

As Adam Rosenfield said, it does say in the header that it is obsolete, but if thats true, could I still compile and run it with an older version of the toolchain? or what has it been replaced with? does anyone know?


  1. Are you sure you are running as root?
  2. Are you sure the process 24269 is still running?

I have no problem running this code (with sudo) on Mac OS X 10.6.8 with any running process:

#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;
}

For example, here is my result with pid 182 (Dock)

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

精彩评论

暂无评论...
验证码 换一张
取 消