quanrock
quanrock

Reputation: 89

How can I get the processID created by popen?

I have to execute command and return the result like cmd.

I just found out the only method for this requirement.I used popen function to execute command and return the result,and then used pclose() function to close the stream and process.

But if commands are never end,for example “ping 8.8.8.8 –t” ,I can’t close process by using pclose() function.

If I kill the child process created by popen() by task manager,the pclose function works OK.

How can I get the processID created by popen to kill ?

===================
And :
If I use _popen() in windows,what will I have to do to get PID?

Upvotes: 0

Views: 2849

Answers (3)

liangdong from baidu
liangdong from baidu

Reputation: 351

wrapp a popen function by yourself with 'pipe + fork + dup2 + exec('/bin/bash', '-c', yourCommandHere)'

Upvotes: 1

Saravanan
Saravanan

Reputation: 1440

Use the

   ps -o user,pid,ppid,command -ax | grep <process name>

to get all the child process information. Actually popen() does the pipe() mechanish to execute the command. Refer man page for popen()

In the man page,

     The environment of the executed command  will  be  as  if  a
 child  process  were  created  within the popen() call using
 fork(2). If  the  application  is  standard-conforming  (see
 standards(5)), the child is invoked with the call:

 execl("/usr/xpg4/bin/sh", "sh", "-c",command, (char *)0);

 otherwise, the child is invoked with the call:

 execl("/usr/bin/sh", "sh", "-c",command, (char *)0);

 The pclose() function closes a stream opened by  popen()  by
 closing  the  pipe.  It  waits for the associated process to
 terminate and returns the termination status of the  process
 running  the command language interpreter. This is the value
 returned by waitpid(3C).

It clearly stats that popen uses pipe and fork with execl for processing the popen() function. So, you can use ps with aux to get the all th child process information.

Upvotes: 0

Alexis Wilke
Alexis Wilke

Reputation: 20720

popen() is written using execve() or some other exec function.

What you do is (1) create a pair of pipes with... pipe() which give you two file descriptor. One is for the stdin and the other for stdout. Then you fork() and do execve() in the child process. At the time you called fork() you get the child process.

The file returned by popen() is a FILE*, to get that from pipe() you have to do an fdopen(). Not too hard.

That's quite a bit of work, but if you need the identifier...

Now... under MS-Windows, that's a bit different, you want to use CreatePipe() and CreateProcess() or similar functions. But the result is similar.

Upvotes: 0

Related Questions