如何等待进程子进程?
我执行通常的 fork + exec 组合:
int sockets [2];
socketpair (AF_LOCAL, SOCK_STREAM, 0, sockets);
int pid = fork ();
if (pid == 0) {
// child
dup2 (sockets[0], STDIN_FILENO);
dup2 (sockets[0], STDOUT_FILENO);
execvp (argv[0], argv);
_exit (123);
}
// parent
close (sockets[0]);
// TODO wait and see if child crashes
是否可以等到子进程崩溃或开始等待 read(...) ?
I do the usual fork + exec combination:
int sockets [2];
socketpair (AF_LOCAL, SOCK_STREAM, 0, sockets);
int pid = fork ();
if (pid == 0) {
// child
dup2 (sockets[0], STDIN_FILENO);
dup2 (sockets[0], STDOUT_FILENO);
execvp (argv[0], argv);
_exit (123);
}
// parent
close (sockets[0]);
// TODO wait and see if child crashes
Is it possible to wait until child crashes or begins waiting on read(...)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
结帐 waitpid
来自
checkout waitpid
from
您可以使用 ptrace(2) 系统调用执行 strace(1) 的操作。在子进程中,在执行之前,您需要调用 PTRACE_TRACEME,这会将父进程作为调试器附加到它。然后父进程必须使用 PTRACE_SYSCALL 恢复执行,并且它将在每个系统调用处停止。父级应使用 wait(2) 等待子级在系统调用处跳闸,然后使用 ptrace 和 PTRACE_PEEK* 来检查系统调用的参数。重复此操作,直到调用您正在等待(读取)的系统调用,然后使用 PTRACE_DETACH 与子进程分离。有关如何识别感兴趣的系统调用的详细信息,请参阅 strace 的源代码。如果进程崩溃,等待系统调用将告诉您该进程收到了 SIGSEGV。在这种情况下也不要忘记分离。
You can use the ptrace(2) syscall to do what strace(1) does. In the child process, before exec'ing, you'll need to invoke PTRACE_TRACEME, and that will attach the parent process to it as a debugger. The parent will then have to resume execution with PTRACE_SYSCALL, and it will stop at each syscall. The parent should use wait(2) to wait until the child trips at a syscall, then use ptrace with PTRACE_PEEK* to examine the arguments to the syscall. Repeat that until the syscall you're waiting for (read) is invoked, then detach from the child process with PTRACE_DETACH. Look at the source of strace for details on how to recognize the syscall of interest. If the process crashes, the wait syscall will tell you that the process got SIGSEGV. Don't forget to detach in that case, too.
这里有一个建议:
打开一个 管道,子进程可以通过管道发送消息告诉父级它将在标准输入上读取()。我认为,如果您正确执行此操作并且孩子死亡,则父母将收到管道已损坏的通知。
Here's a suggestsion:
Open a pipe, the child process can send a message down the pipe to tell the parent that it is about to read() on stdin. If you do this correctly and the child dies, the parent will be notified that the pipe has been broken, I think.