更改进程的父进程
是否可以更改进程父进程?
例如:父进程A有子进程B,我可以在不杀死A的情况下使B的父进程成为Init进程吗?
Is it possible to change a process parent?
ex: parent A has Child B can I make the parent of B is the Init process without killing A?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是从进程 B 的外部。
从进程 B 的内部,您可以调用 fork 来复制您的进程,然后让原始进程退出。当这种情况发生时,新副本 B2 将不再是 A 的子进程,其父进程将被设置为 1(init 进程)。
Not from outside of process B.
From inside process B, you can call fork which makes a copy of your process, then let the original exit. When that happens the new copy B2 will not be a child of A, its parent will be set to 1 (the init process).
调用 ptrace(PTRACE_ATTACH, pid, x, y) ,其中 pid 是 B 的 pid(在您的示例中),x 和 y 并不重要(可能将它们设置为NULL)将使调用进程成为 B 的父进程,用于许多(但不是全部)目的(当然,基于进程的用户 ID 进行限制,以防止您接管其他人的进程,除非您是 root)。
调用 ptrace(PTRACE_ATTACH, 后,子进程仍会从
getppid()
获取其原始父进程或 init 的 pid 作为其父进程 pid,但跟踪进程将能够调用wait
并从进程 B 获取SIGCHLD
。这里发生了很多事情,因此您应该阅读
man 2 ptrace
并确保您非常了解细节。Calling
ptrace(PTRACE_ATTACH, pid, x, y)
wherepid
is the pid of B (in your example) and x and y don't matter (probably set them to NULL) will make the calling process the parent of B for many (but not all) purposes (with restrictions based on user ID of the processes, of course, to keep you from taking over someone else's processes unless you are root).After calling
ptrace(PTRACE_ATTACH,
the child will still get either its original parent or init's pid as its parent pid fromgetppid()
, but the tracing process will be able to callwait
and getSIGCHLD
from process B.There is a lot of stuff going on here, so you should read
man 2 ptrace
and make sure you understand the details pretty well.