views:

62

answers:

4

I am trying to display currently running process in Ubuntu.

Right now I am using system() function to print running process in the terminal. Code:

system("ps -A");

This function displays all running process in the terminal.

But I want to this functionality using a POSIX function. I am not looking for a ready made code.

Can some one point me to the function name or any manual ?

+1  A: 

As far as I know does ps on Linux internally loop over the directories (corresponding to process ids) found under /proc. So I think there is no single function doing that, you'd have to loop over the subdirectories of /proc yourself (using more generic POSIX functions such as readdir etc.).

Andre Holzner
How do I include proc in my program?
Searock
`/proc` should be a directory on your file system. You can get a list of its contents using the function `readdir` (see the `readdir` manpage by doing `man readdir` on a shell).
Andre Holzner
thanks for the advice I will give it a try.
Searock
+1  A: 

Take a look at popen

codaddict
Should I pass "ps -A" to pclose() and store the output into some array or buffer?
Searock
This question will answer you doubt: http://stackoverflow.com/questions/839232/popen-in-c
codaddict
+1  A: 

But I want to this functionality using a POSIX function. I am not looking for a ready made code.

No POSIX function exists to list running processes. That is OS specific, not portable, rarely needed by applications and thus not part of POSIX.

But since you need this on Linux, the most POSIXy solution would be to use functions opendir()/readdir()/closedir() to iterate over the content of /proc special file system.

All numeric entries in the directory are PIDs of running processes. Check the content the man 5 proc for details what information about the running processes can be obtained from there. Then you can use the open()/read()/close() or readlink() calls to retrieve the information about a particular process from the /proc/NNN/* files.

On Linux, the standard tools like ps and top use the /proc to gather the information about processes. It is official Linux' interface to the information about running processes.

Dummy00001
+1 thanks for the advice.
Searock
+2  A: 

ps is a POSIX command.

popen is a POSIX API for reading output from a command.

If you want a pure POSIX approach (maybe you want it portable to some OS that does not provide /proc), you should run ps with POSIX-only options and fetch the output from popen.

So, for example, maybe you want to call popen("ps -A -o pid=", "r"); and then read through the list of PIDs.

bstpierre
+1 I'll try both examples.
Searock