Need to get the PID of a process

How do I run a process from a C++ program and obtain its PID? Right now I am doing in a "parallel" thread:

 
system("ampl method.run");


and into the main function (after running the thread mentioned before):

1
2
sleep(5); //Just to be sure that the thread is executing the ampl command
system("ps -Ac| grep ampl | awk '{print $1}' > ~/AMPL_PID.txt");


This doesn't work. The main program hangs in the "system" function while the thread continues to execute. Once I manually kill the ampl process in the thread, the main program continues and writes the system("ps -Ac...") output to the desired location.

I need to be able to obtain the ampl command PID in order to later kill it (if necessary). Any ideas how to make this work or how to do this?
Use fork() and exec().

fork() creates a child process. The parent receives the PID of the child.
The child should then exec() whatever it is you want to run.
With system(), you can't (not easily, anyway).
http://linux.die.net/man/3/posix_spawnp
http://linux.die.net/man/3/popen

Hope this helps.

[edit] yoink! too late. I should mention that using fork() and exec() together are more likely to be available than spawn()...
Last edited on
Use pgrep


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>

#ifdef WIN32
FILE *popen ( const char* command, const char* flags) {return _popen(command,flags);}
int pclose ( FILE* fd) { return _pclose(fd);}
#endif

int main(int argc, char* argv[])
{
class="quote">
class="qd"> char psBuffer[128]; FILE *iopipe; if( (iopipe = popen( "pgrep ampl", "r" )) == NULL )exit( 1 ); //ampl is the command (executable) whose pid you want to find while( !feof( iopipe ) ) { if( fgets( psBuffer, 128, iopipe ) != NULL ) puts( psBuffer ); // or use atoi(psBuffer) to get numerical value } printf( "\nProcess returned %d\n", pclose( iopipe ) );
return 0; }



use quoted part in your other thread
Topic archived. No new replies allowed.