如何在 Perl 中向已打开的进程发送信号?
我编写了一个简单的 Perl 脚本,它将在 while 循环中运行,并在任何信号发送到此 Perl 脚本时退出。我编写了一个 ac 程序,该程序使用 pthread_create()
创建一个线程,并在其启动例程中,它使用 popen
来执行该 Perl 脚本:
popen("/usr/bin/perl myprog.pl");
我正在使用 sigtrap
在 Perl 脚本中捕获它接收到的任何信号。现在我想从我的 C 程序向该线程执行的 Perl 进程发送信号 (TERM)。我怎样才能做到这一点?有什么方法可以向 popen
的进程发送信号。如果需要更多详细信息,请告诉我。
I wrote a simple Perl script which will run in while loop and exit whenever any signal is send to this Perl script. I wrote a c program which creates a thread using the pthread_create()
and in its start routine, it's using popen
to execute that Perl script:
popen("/usr/bin/perl myprog.pl");
I am using the sigtrap
in the Perl script to catch any signal it receives. Now I want to send signal (TERM) from my C program to this Perl process executed by the thread. How can I do that? Is there any way to send a signal to popen
'ed processes. Please let me know if need more details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发送信号通常使用
kill
。为了能够杀死您通常需要您想要发送信号的进程的进程 ID、PID。popen
不会给你这个。不过,还有一些替代方案:您可以使用 PID
0
,这会将信号发送到进程组中的每个进程。如果只有一个父进程使用popen
生成一个子进程,那么使用kill(0, your_signal)
将是一种方法。另一种方法是让子进程将其 PID 传回父进程,例如,在启动后第一件事就是在一行上输出它。
在 Perl 中,这看起来就像
执行
popen
的进程可以从它获得的文件句柄中读取该行,并使用strtol
或从中提取有用的 pid >atoi
,并保留它,以便稍后在读取其子进程的实际输出后与kill
一起使用。如果出于某种原因,这些方法都无法解决您的问题,您可能希望完全停止使用 popen,并手动执行大部分操作,最重要的是 fork code>ing,因为这将为您提供 PID,以便稍后发送信号。
Sending signals usually works using
kill
. In order to be able to kill you normally need the process id, PID, of the process you want to signal.popen
doesn't give you that. However, there's a couple of alternatives:You could use a PID of
0
, which would send your signal to every process in the process group. If you only have one parent process spawning one child process usingpopen
, then usingkill(0, your_signal)
would be one way to go.Another way to go would be to have the child process communicate its PID back to the parent process by, for example, just outputing that on a single line as the first thing after starting up.
In perl, that'd look like
the process that did
popen
could then read that line from the filehandle it got, and extract a useful pid from that usingstrtol
oratoi
, and keep that around to use withkill
later on, after having read the actual output of its child process.If, for whatever reason, none of these approaches is viable for your problem, you probably want to stop using
popen
alltogether, and do most of what it does manually, most importantly thefork
ing, as that's what'll give you the PID to use to later send signals.popen()
没有给你任何方法来访问子进程的 PID,而你需要它来向它发出信号。您需要自己完成
popen()
的繁琐工作(设置管道、fork、exec、等待)。popen()
doesn't give you any way to access the PID of the child process, which you need in order to signal it.You will need to do the gory work of
popen()
yourself (set up pipes, fork, exec, wait).