Get all process list linux

How to list all the running processes by using UNIX-C/C++

I want to list all of the processes in the system. I used to use shell command «ps» and system function to get the result. However, it seems a little complex. How to use UNIX C functions to complete this job.

8 Answers 8

Under Linux you can examine the pseudo filesystem /proc for process information. That means using the opendir() set of functions and looking for sub-directories that are numbers — these are the process identifiers of each of the processes running on the system. There are numerous files within each sub-directory, that can be opened and read using open()/read() as long as your process has the required privileges.

manpage for more details of the information available to you.

While you’re definitely encouraged to browse the pseudo /proc filesystem, from a C/C++ program you should be using proc/readproc.h that is part of libprocps and is capable of accessing the same information.

E.g. on Debian based distribution you’ll need to install libprocps-dev :

You can list your processes this way, see man openproc for available flags:

#include #include #include #include using std::cout; int main() < PROCTAB* proc = openproc(PROC_FILLMEM | PROC_FILLSTAT | PROC_FILLSTATUS); proc_t proc_info; memset(&proc_info, 0, sizeof(proc_info)); cout closeproc(proc); return 0; > 
g++ -g -Wall -O2 readps.cc -o readps -lprocps 

ps is the standard, for better or worse. It has many under-appreciated formatting options that can simplify your cross-platform parsing of its output.

/proc is more convenient, but not portable, and might be unavailable locally even where supported (e.g., in a chroot environment).

There is a finish solution for this.

clone it using git and do what you want.

#include"read_proc.h" int main(void) < struct Root * root=read_proc(); struct Job * buffer; int i=0; for(;ilen;i++) < buffer=get_from_place(root,i); printf("%s\t%u\n",buffer->name,buffer->pid); > return 0; > 

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

There are no standards for finding process information; each Unix vendor gets to provide their own mechanism for providing information to system administrators.

Linux and Solaris use the /proc/ filesystem to export information on processes to userspace, but I do not think they are at all compatible. (I have a vague recollection that Solaris decided to export all its information in a binary format to remove in-kernel processing, at the expense of more closely tying userspace programs to kernel datastructures. The top program used to be very good at peeking into kernel memory to read process tables, I’m not sure it needs to any more, but maybe all the historical knowledge is still baked in.)

Читайте также:  Команды для настройки linux

If you want to be platform-specific, the Linux proc(5) manpage has the information you need. Happy hacking. 🙂

Источник

Getting List of Running processes and applications

How can I see which application and what processes are running recently after the login using terminal command.

2 Answers 2

Generally ps command does it.

If you type man ps , you will get the manual for this command, and there you can check which flag you will need. For example, ps -e will list all running processes in the system.

Another command is top which will show an active view of all running process.

The following script lists all processes, and splits them in applications and other processes.

As definition for an application, I practice that the process is initiated from a .desktop file (since practically all applications are represented by a .desktop file), and that the .desktop file appears in Dash (the .desktop file has no line: NoDisplay=true ).

Work to be done:

The script, as it is, derives the application’s process name from the (last section of-) the command, found in the desktop file, and also from information, found in the possible symlinks it might refer to (e.g. in case of LibreOffice > process name: soffice.bin ). In some cases however, an application runs from a remote script, called from the .desktop file. In those cases, the process will not be recognized as an application.

The script gives an output like:

Processes, related to applications: PID TTY TIME CMD 1933 ? 00:03:55 firefox 18091 ? 00:00:00 dia 18162 ? 00:00:01 soffice.bin 31167 ? 00:00:06 alarm-clock-app 31174 ? 00:00:09 nautilus 31301 ? 00:00:20 dropbox 31998 ? 00:01:35 idle3 Other processes: PID TTY TIME CMD 1 ? 00:00:01 init 2 ? 00:00:00 kthreadd 3 ? 00:00:02 ksoftirqd/0 5 ? 00:00:00 kworker/0:0H 7 ? 00:00:15 rcu_sched 8 ? 00:00:08 rcuos/0 
#!/usr/bin/env python3 import os import subprocess def createlist_appcommands(): dtfile_dir = "/usr/share/applications" dtfile_list = [item for item in os.listdir(dtfile_dir) if item.endswith(".desktop")] commands = [] for item in dtfile_list: try: with open(dtfile_dir+"/"+item) as data: searchlines = data.readlines() command = [line for line in searchlines if line.startswith("Exec=") and not "NoDisplay=true\n" in searchlines ][0].replace("Exec=", "").replace("\n", "").split("/")[-1].split(" ")[0] commands.append(command) except Exception: pass return commands + [trace_symlinks(item) for item in commands if not trace_symlinks(item)== None] def trace_symlinks(command): target = subprocess.Popen(["which", command], stdout=subprocess.PIPE) location = (target.communicate()[0].decode("utf-8")).split("\n")[0] check_filetype = subprocess.Popen(["file", location], stdout=subprocess.PIPE) filetype = (check_filetype.communicate()[0].decode("utf-8")).split("\n")[0] if "symbolic link" in filetype: return filetype.split("/")[-1].replace("' ", "") else: pass def createlist_runningprocs(): processesb = subprocess.Popen(["ps", "-e"], stdout=subprocess.PIPE) process_listb = (processesb.communicate()[0].decode("utf-8")).split("\n") linked_commands = [(item, item[24:]) for item in process_listb][1:] applist = createlist_appcommands() print("Processes, related to applications:\n PID TTY"+" "*10+"TIME CMD") matches = [] for item in applist: for i in range(0, len(linked_commands)): if item[:15] in linked_commands[i][1] and len(item[:15])/len(linked_commands[i][1]) > 0.5: matches.append(i) matches = sorted(matches) for i in range(0, len(linked_commands)): if i in matches: print(linked_commands[i][0]) print("\nOther processes:\n PID TTY"+" "*10+"TIME CMD") for i in range(0, len(linked_commands)): if not i in matches: print(linked_commands[i][0]) createlist_runningprocs() 

Copy the script in an empty file, save it as processes.py , run it by the command:

python3 /path/to/processes.py 

Edit: updated my answer, rewrote the script.

  • (much) better performance
  • the script now traces and recognizes applications, initiated via symlinks (which may have another process name). Although exceptions are always possible, they should be rare now.

Источник

Читайте также:  Fallout 2 linux русификатор

Linux List Processes – How to Check Running Processes

Bolaji Ayodeji

Bolaji Ayodeji

Linux List Processes – How to Check Running Processes

Every day, developers use various applications and run commands in the terminal. These applications can include a browser, code editor, terminal, video conferencing app, or music player.

For each of these software applications that you open or commands you run, it creates a process or task.

One beautiful feature of the Linux operating system and of modern computers in general is that they provide support for multitasking. So multiple programs can run at the same time.

Have you ever wondered how you can check all the programs running on your machine? Then this article is for you, as I’ll show you how to list, manage, and kill all the running processes on your Linux machine.

Prerequisites

  • A Linux distro installed.
  • Basic knowledge of navigating around the command-line.
  • A smile on your face 🙂

A Quick Introduction to Linux Processes

A process is an instance of a running computer program that you can find in a software application or command.

For example, if you open your Visual Studio Code editor, that creates a process which will only stop (or die) once you terminate or close the Visual Studio Code application.

Likewise, when you run a command in the terminal (like curl ifconfig.me ), it creates a process that will only stop when the command finishes executing or is terminated.

How to List Running Processes in Linux using the ps Command

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.

To test this, just open your terminal and run the ps command like so:

Screenshot-2021-06-28-at-3.25.33-PM

This will display the process for the current shell with four columns:

  • PID returns the unique process ID
  • TTY returns the terminal type you’re logged into
  • TIME returns the total amount of CPU usage
  • CMD returns the name of the command that launched the process.

You can choose to display a certain set of processes by using any combination of options (like -A -a , -C , -c , -d , -E , -e , -u , -X , -x , and others).

If you specify more than one of these options, then all processes which are matched by at least one of the given options will be displayed.

Screenshot-2021-06-28-at-3.55.10-PM

Type man ps in your terminal to read the manual for the ps command, which has a complete reference for all options and their uses.

To display all running processes for all users on your machine, including their usernames, and to show processes not attached to your terminal, you can use the command below:

Читайте также:  Hp 1132 драйвер линукс

Here’s a breakdown of the command:

Screenshot-2021-06-28-at-4.39.05-PM

  • ps : is the process status command.
  • a : displays information about other users’ processes as well as your own.
  • u : displays the processes belonging to the specified usernames.
  • x : includes processes that do not have a controlling terminal.

This will display the process for the current shell with eleven columns:

  • USER returns the username of the user running the process
  • PID returns the unique process ID
  • %CPU returns the percentage of CPU usage
  • %MEM returns the percentage memory usage
  • VSV returns the virtual size in Kbytes
  • RSS returns the resident set size
  • TT returns the control terminal name
  • STAT returns the symbolic process state
  • STARTED returns the time started
  • CMD returns the command that launched the process.

How to List Running Processes in Linux using the top and htop Commands

You can also use the top task manager command in Linux to see a real-time sorted list of top processes that use the most memory or CPU.

Type top in your terminal and you’ll get a result like the one you see in the screenshot below:

Screenshot-2021-06-28-at-4.27.28-PM

An alternative to top is htop which provides an interactive system-monitor to view and manage processes. It also displays a real-time sorted list of processes based on their CPU usage, and you can easily search, filter, and kill running processes.

htop is not installed on Linux by default, so you need to install it using the command below or download the binaries for your preferred Linux distro.

sudo apt update && sudo apt install htop

Just type htop in your terminal and you’ll get a result like the one you see in the screenshot below:

Screenshot-2021-06-29-at-4.49.09-AM

How to Kill Running Processes in Linux

Killing a process means that you terminate a running application or command. You can kill a process by running the kill command with the process ID or the pkill command with the process name like so:

To find the process ID of a running process, you can use the pgrep command followed by the name of the process like so:

To kill the iTerm2 process in the screenshot above, we will use any of the commands below. This will automatically terminate and close the iTerm2 process (application).

Conclusion

When you list running processes, it is usually a long and clustered list. You can pipe it through less to display the command output one page at a time in your terminal like so:

or display only a specific process that matches a particular name like so:

I hope that you now understand what Linux processes are and how to manage them using the ps , top , and htop commands.

Make sure to check out the manual for each command by running man ps , man top , or man htop respectively. The manual includes a comprehensive reference you can check if you need any more help at any point.

Thanks for reading – cheers! 💙

Источник

Оцените статью
Adblock
detector