Display all process using a posix function

前端 未结 4 942
一生所求
一生所求 2020-12-06 21:38

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         


        
相关标签:
4条回答
  • 2020-12-06 21:39

    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.

    0 讨论(0)
  • 2020-12-06 21:40

    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.).

    0 讨论(0)
  • 2020-12-06 21:56

    Take a look at popen

    0 讨论(0)
  • 2020-12-06 21:59

    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.

    0 讨论(0)
提交回复
热议问题