开发者

How can I send a signal to a popen'ed process in Perl?

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开发者_StackOverflow社区 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.


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 using popen, then using kill(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

print $$, "\n";

the process that did popen could then read that line from the filehandle it got, and extract a useful pid from that using strtol or atoi, and keep that around to use with kill 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 the forking, as that's what'll give you the PID to use to later send signals.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜