LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 06-09-2005, 02:18 PM   #1
appforce
LQ Newbie
 
Registered: Jun 2005
Posts: 10

Rep: Reputation: 0
How to get how many processes running on a Linx machine?


Hi! All:
I know that /proc/ provides one dirctory to store the useful information for each process! But is there any way to get how many processes currently running on a machine, and get a list of pid? Thank you very much!
 
Old 06-09-2005, 02:22 PM   #2
masand
LQ Guru
 
Registered: May 2003
Location: INDIA
Distribution: Ubuntu, Solaris,CentOS
Posts: 5,522

Rep: Reputation: 69
try

ps aux

man ps

will help u more

regards
 
Old 06-09-2005, 03:15 PM   #3
junaid18183
Member
 
Registered: Mar 2005
Location: India
Distribution: RedHat 9.0 and EL
Posts: 31

Rep: Reputation: 15
ps is verey useful as masand suggested

take a look of pstree and top also.
 
Old 06-09-2005, 03:36 PM   #4
appforce
LQ Newbie
 
Registered: Jun 2005
Posts: 10

Original Poster
Rep: Reputation: 0
Thank you very much! But I just hope I can write a program to minitor the information for the processes such like "top" . I just wanna know there is any API wich can get how many processes running on a linux machine and get the pid list! Thanks!
 
Old 06-09-2005, 03:57 PM   #5
masand
LQ Guru
 
Registered: May 2003
Location: INDIA
Distribution: Ubuntu, Solaris,CentOS
Posts: 5,522

Rep: Reputation: 69
if u use kde then u can use the kde system monitor

regards
 
Old 06-09-2005, 10:50 PM   #6
randyding
Member
 
Registered: May 2004
Posts: 552

Rep: Reputation: 31
I believe programs like ps and top simply view the contents of the /proc directory. The directories that are pure numbers are all the running process id.
 
Old 06-09-2005, 11:28 PM   #7
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 59
If nothing else you could use this program:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

int is_all_digits(char *str)
{
  while(*str)
  {
    if(!isdigit(*str))
      break;
    str++;
  }

  return *str ? 0 : 1;
}

int main(void)
{
  DIR *dir;
  struct dirent *dent;
  struct stat stbuf;
  char buf[PATH_MAX];

  if(!(dir = opendir("/proc")))
  {
    perror("opendir()");
    exit(EXIT_FAILURE);
  }

  while((dent = readdir(dir)))
  {
    if(!is_all_digits(dent->d_name))
      continue;

    snprintf(buf, PATH_MAX, "/proc/%s", dent->d_name);
    if((stat(buf, &stbuf)) == -1)
    {
      perror("stat()");
      continue;
    }

    if(S_ISDIR(stbuf.st_mode))
      puts(dent->d_name);
  }

  closedir(dir);

  return EXIT_SUCCESS;
}
Code:
itsme@dreams:~/C$ ./listpids | head
1
2
3
4
5
6
7
84
90
93
itsme@dreams:~/C$
 
Old 06-10-2005, 11:21 AM   #8
appforce
LQ Newbie
 
Registered: Jun 2005
Posts: 10

Original Poster
Rep: Reputation: 0
Thank you very much!
 
Old 07-24-2005, 12:07 PM   #9
fortezza
Member
 
Registered: Mar 2003
Location: Colorado
Distribution: Fedora Core 4
Posts: 297

Rep: Reputation: 30
What if you are just looking to see if a particular process is running ( via C/C++ ) by name, how could that been done?
 
Old 07-24-2005, 01:31 PM   #10
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: Debian
Posts: 2,536

Rep: Reputation: 111Reputation: 111
Quote:
Originally posted by fortezza
What if you are just looking to see if a particular process is running ( via C/C++ ) by name, how could that been done?
Changed the code itsme86 posted to do that:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

int checkexe(char *pid, char *searchexe)
{
    int len;
    char *exefile;
    char exepath[PATH_MAX];
    char symlink[PATH_MAX];

    /* Symlink /proc/<pid>/exe points to the executable file
     * which is running in the process.
     *
     * Resolve the symlink, remove the directory part of the path,
     * and compare that to the exe-name we are looking for.
     */
    
    snprintf(symlink, PATH_MAX, "/proc/%s/exe", pid);
    len = readlink(symlink, exepath, PATH_MAX);

    /* Catch some readlink() errors: */
    if (len >= PATH_MAX) {
        fprintf(stderr, "Path for pid #%s too long. Truncated.\n", pid);
        return 0;
    }
    if (len < 0) {  /* Often harmless error, e.g. "permission denied". */
        return 0;   /* No error message, just returning false silently here. */
    }
    exepath[len] = '\0';

    /* Skip directory part of the path to get to the filename */
    exefile = strrchr(exepath, '/');
    if (exefile == NULL) 
        exefile = exepath;
    else if (++exefile == '\0')
        exefile = exepath;

    /* Compare the exe-name searching for with the file-name linked to
     * by /proc/<pid>/exe.
     */
    return !strcasecmp(exefile, searchexe);
}


int is_all_digits(char *str)
{
    while (*str) {
        if (!isdigit(*str))
            break;
        str++;
    }

    return *str ? 0 : 1;
}


int main(int argc, char *argv[])
{
    DIR *dir;
    struct dirent *dent;
    struct stat stbuf;
    char procpath[PATH_MAX];

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <process executable name>\n\n", *argv);
        exit(EXIT_FAILURE);
    }

    if (!(dir = opendir("/proc"))) {
        perror("opendir()");
        exit(EXIT_FAILURE);
    }

    while ((dent = readdir(dir))) {
        if (!is_all_digits(dent->d_name))
            continue;

        snprintf(procpath, PATH_MAX, "/proc/%s", dent->d_name);
        if ((stat(procpath, &stbuf)) == -1) {
            perror("stat()");
            continue;
        }

        if (S_ISDIR(stbuf.st_mode))
            if (checkexe(dent->d_name, argv[1]))
                printf("%s is running in PID #%s.\n", argv[1], dent->d_name);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}
It checks the /proc/<pid>/exe symlinks for the name. It works well, but now I started thinking it may be better to read the /proc/<pid>/cmdline files to check for the name, because non-privileged users more often have permissions to read /proc/<pid>/cmdline than to resolve the /proc/<pid>/exe symlink.

OTOH, I think /proc/<pid>/exe may be more accurate.
 
Old 07-24-2005, 07:22 PM   #11
fortezza
Member
 
Registered: Mar 2003
Location: Colorado
Distribution: Fedora Core 4
Posts: 297

Rep: Reputation: 30
The overrall goal was to write a C++ program that could detect if a process was running and start it in the correct display if it wasn't.

Here is what just got working about 20 minutes ago. It needs some cleanup/commenting/error checking, but for now it gets the job done. The hard part was starting the process and then exiting, since every C++ function to start a process insists on waiting the the process to end. My workaround was to start the process under a thread, detach the thread, wait for the process to be in the process list, and then exit the main program. My compiler won't let me terminate the program until the child process is closed, but from the command line it works fine ( starts the external program and exits ).


Here it is:

Code:
#include <pthread.h>
#include <iostream.h>
#include <unistd.h>


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream.h>
#include <iostream.h>
#include <string.h>
#include <sys/signal.h>
#include <unistd.h>
#include <fcntl.h> 



using namespace std;


class Thread {
	private:
		pthread_t thread;
		static void * dispatch(void *);
	protected:
		virtual void run() = 0;
	public:
		virtual ~Thread();
		void start();
		void join();
		void detach();
};



Thread::~Thread()
{}

void * Thread::dispatch(void * ptr)
{
	if (!ptr) return 0;
	static_cast<Thread *>(ptr)->run();
	pthread_exit(ptr);
	return 0;
}

void Thread::start()
{
	pthread_create(&thread, 0, Thread::dispatch, this);
}

void Thread::join()
{
	pthread_join( thread, 0 );
	//pthread_join(thread, 0);
}

void Thread::detach() {
	pthread_detach( thread );

}


class Test : public Thread
{
	private:
		string image;
		string display;
	protected:
		virtual void run();
	public:
		Test(string image, string display ) : image(image),display(display) {}
};

void Test::run()
{
	//cout << "Starting Amule!\n";
	char buf[100];
	if ( display.length()  ) {
		sprintf( buf, "DISPLAY=\":0.%s\" %s &",display.c_str(),image.c_str() ); 
	}
	else {
		sprintf( buf, "DISPLAY=\":0.0\" %s &", image.c_str() ); 
	}
	
	system( buf );
}


using namespace std;


bool isRunning( string procName );

int is_all_digits(char *str)
{
  while(*str)
  {
    if(!isdigit(*str))
      break;
    str++;
  }

  return *str ? 0 : 1;
}


int main( int argc, char *argv[] )
{
	Test *a;
	if ( argc == 2 ) {
		a = new Test( argv[1], ""  );
	}
	else if ( argc ==3 ) {
		a = new Test( argv[1], argv[2]  );
	}
	else {
		cout << "Command syntax is: startproc <image name> <display 0>." << endl;
		return 1;
	}
	a->start();
	a->detach();
	while ( not isRunning( argv[1] ) ) {
		usleep( 1000 );
	}
	return 0;
}

bool isRunning( string procName ) {

  DIR *dir;
  struct dirent *dent;
  struct stat stbuf;
  char buf[PATH_MAX];
  bool found = false;
  if(!(dir = opendir("/proc")))
  {
    perror("opendir()");
    exit(EXIT_FAILURE);
  }

  while((dent = readdir(dir)))
  {
    if(!is_all_digits(dent->d_name))
      continue;
	char filepath[2000];
	char str2[2000];
	sprintf( filepath, "/proc/%s/cmdline",dent->d_name );
    fstream file_op( filepath ,ios::in);
	while ( ! file_op.eof() ) {
		file_op.getline( str2, 2000 );
		string strName( str2 );
		int index = strName.find( procName );
	    //snprintf(buf, PATH_MAX, "str=%s", str);
		if ( index >= 0 ) {
			//printf( "Command=%s, index=%d\n", strName.c_str(), index );
			found = true;
			break;
			//cout << strName << endl;
		}
	}	  
	file_op.close();
  }
  if ( found ) {
  	printf( "%s is running :)\n", procName.c_str() );
	//return true;
  }
  else {
  	printf( "%s is not running :(\n", procName.c_str() );
  }
  closedir(dir);
  return found;

}
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
perl/bash script to monitor all processes running in my machine pudhiyavan Linux - Security 4 07-19-2005 02:09 PM
Too many Running Processes AdamCo Linux - Software 5 10-22-2004 02:17 AM
processes running true_atlantis Slackware 2 02-27-2004 02:34 AM
need running processes amrogers3 Linux - Newbie 4 02-24-2004 08:23 AM
seeing running processes albean Linux - Newbie 3 11-11-2002 06:52 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:29 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration