|
-
January 24th, 2002, 10:38 AM
#1
LINUX - ENUM PROCESSES
How do i enumerate processes in linux similar to windows EnumProcesses()? I know ps returns that kind of information but that is not what i am looking for. Basically i want to know if a specific app/process is running... thanks, any help is appreciated..
-
January 24th, 2002, 05:23 PM
#2
A first attempt..
getpid is a function but of course that only returns the process id of the calling process.
This is what I'd do. It will work if your environment is set up correctly. you need to have grep in the path is all. Could use a little work on error checking if you think the approach shows promise...
You can see what I'm doing by running the comand I'm using from the command line.
"ps | grep processname".
If you want the process ID you can easily modify the function I wrote bellow aditionally take advantage of awk. Or you could just parse the string returned from the grep output. Both the parent process ID and process ID are present there.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
// Function Proto's...
int MyEnumProcess( char *pszProcessName );
// Main Process
void main( void )
{
if ( MyEnumProcess( "dclock") )
{
printf( "Process dclock is running");
}
else
{
printf( "Process dclock is not running");
}
}
// Function
int MyEnumProcess( char *pszProcessName )
{
char psBuffer[1024];
char szCommandline[100] = "";
int iRc = 0;
FILE *chkdsk;
// formate your command line expression
sprintf( szCommandline, "ps | grep %s", pszProcessName );
//Run the command line so that it writes its output to a pipe. Open this
//pipe with read text attribute so that we can read it
//like a text file.
if( (chkdsk = _popen( szCommandline, "rt" )) == NULL )
exit( -1 );
// Read pipe their should only be one line output from the command line either
if( !feof( chkdsk ) )
{
// the process is present or it is not...
// The buffer I'm using has room for like 10 lines
// if the output is larger we don't really care..
// all we're interested in is T/F right...
if( fgets( psBuffer, 1024, chkdsk ) != NULL )
{
// Does the process name exist in the output??
if ( strstr( psBuffer, pszProcessName ) != NULL )
{ // found your process Eurika
iRc = 1;
}
}
}
// Close pipe
_pclose( chkdsk );
return ( iRc );
}
Another powerful method to accomplish Unix Systems programming would be to write a generic function to run shell scripts and parse their output. Then all's you would have to do is write a shell script to add major functionality to your program...
Have fun... Rate me!!
-
January 24th, 2002, 06:17 PM
#3
Re: A first attempt..
Thanks for the reply.... i like the approach that you are going on here... it is similar to what i am doing now.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|