问题描述
我有一个运行在伪终端的一个子进程。父进程不以root身份运行,但孩子的过程呢,通过su或sudo的。因为这个原因,不可能将信号发送到子进程,迫使它退出。我想通过这些手段之一,迫使它退出:
I have a child process which runs in a pseudo terminal. The parent process does not run as root, but the child process does, through su or sudo. Because of this it is not possible to send a signal to the child process to force it to exit. I want to force it to exit by one of these means:
- 模拟一个按Ctrl-C。
- 模拟一个终端挂机。
我该怎么做其中任一?我已经有一个pty主FD,我已经试过这样的事情:
How do I do either of these? I already have a pty master fd, and I've tried something like this:
write(master, &termios.c_cc[VINTR], 1)
但它不会做任何事情。
but it doesn't do anything.
推荐答案
我最终与下述溶液中去:
I eventually went with the following solution:
分叉,而不是立即exec'ing须藤之后,我执行exec()的辅助子进程来代替,这反过来叉和高管须藤并呼吁waitpid函数就可以了。所以这个过程的层次结构是这样的:
After forking, instead of exec'ing sudo immediately, I exec() a helper child process instead, which in turn forks and execs sudo and calls waitpid on it. So the process hierarchy looks like this:
original process <---- runs as user
|
+-- helper process <---- runs as user, session leader,
| has own pty, in pty's foreground process group
|
+--- sudo <---- runs as root
通过杀死助手的过程中,PTY没有一个前台进程了。这将导致OS发送SIGHUP到整个前台进程组,无论用户的,所以sudo的是SIGHUP'ed了。
By killing the helper process, the pty does not have a foreground process anymore. This will cause the OS to send SIGHUP to the entire foreground process group, regardless of the user, so sudo is SIGHUP'ed too.
这篇关于如何发送Ctrl-C键控制字符或终端挂断消息,子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!