After opening a pipe to a process with popen
, is there a way to kill the process that has been started? (Using pclose
is not what I want because that will wait for the process to finish, but I need to kill it.)
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- How to let a thread communicate with another activ
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
I simply put in the (bash) script, in the first line:
then I read the pid, and use it to do a : kill(pid,9)
Here is an improved version of popen2 (credit is due to Sergey L.). The version posted by slacy does not return the PID of the process created in popen2, but the PID assigned to
sh
.The new version is to be called with
I have follow idea of @slacy that create function popen2.
But found problem when child process is die, parent process that still read file descripter
outfp
not return from function.That could fix by add close unuse pipe on parent process.
We can get correct pid of new process by using bash as shell.
When child process die the caller of function
popen2
should collect status of child process by callpclose2
. if we don't collect that status child process could be zombie process when it terminate.This is the full code that tested and work as expect.
The obvious way is system("pkill process_name");
Clearly this is problematic if you have more than one instance of the process running.
Actually if the process is doing I/O (which it should be, otherwise why
popen
instead ofsystem
(3)?), thenpclose
should whack it with aSIGPIPE
the next time it tries to read or write, and it should fall over nicely :-)Don't use popen(), and write your own wrapper that does what you'd like.
It's fairly straightforward to fork(), and then replace stdin & stdout by using dup2(), and then calling exec() on your child.
That way, your parent will have the exact child PID, and you can use kill() on that.
Google search for "popen2() implementation" for some sample code on how to implement what popen() is doing. It's only a dozen or so lines long. Taken from dzone.com we can see an example that looks like this:
NB: Seems like popen2() is what you want, but my distribution doesn't seem to come with this method.