reparent指定进程到当前进程

来源:互联网 发布:linux下mysql配置详解 编辑:程序博客网 时间:2024/05/22 15:28

转载时请注明出处和作者联系方式
文章出处:http://www.limodev.cn/blog
作者联系方式:李先静 <xianjimli at hotmail dot com>

今天遇到一个问题,需要监视某个应用程序的退出事件,并得到它的退出码。waitpid只能监视子进程,对其它进程没有效果,怎么才能reparent一个进程呢?我在内核里找了半天也没有找到相应的系统调用,后来想到调试器都可以,那一定有办法。调试器是用ptrace实现的,我试了一下,发现其实很简单。做了些测试,也没有发现性能上的损失,我想这种方法应试是可行的。发出来给有类似需要的朋友参考吧:

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ptrace.h>

int reparent_process(int pid)
{
int ret = ptrace(PTRACE_ATTACH, pid, NULL, NULL);
if(ret == 0)
{
wait(NULL);
ret = ptrace(PTRACE_CONT, pid, NULL, NULL);
}

return ret;
}

int main(int argc, char* argv[])
{
int ret = 0;
pid_t pid = 0;
int status = 0;

if(argc != 2)
{
printf("Usage: %s pid/n", argv[0], pid);
return 0;
}

pid = atoi(argv[1]);
reparent_process(pid);

ret = waitpid(pid, &status, 0);
printf("%s:%d pid=%d ret=%d status=%x/n", __func__, __LINE__, pid, ret, status);

return 0;
}
原创粉丝点击