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:
sy
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.
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.).
Take a look at popen
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.