fbpx Manage Processes in Linux: ps, kill, top, bg and fg | Certificação Linux

Mastering Linux Processes: Complete Command Guide

📅 05/11/2022 ⏱ 23 min ✍️ Uira Ribeiro
Linuxhow-to
Mastering Linux Processes: Complete Command Guide
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

Do you know how to execute commands to manage processes in Linux? This is a natural difficulty for all users and programmers, beginners or even intermediate, in the Linux universe.

Knowing which commands should be used for each function is a responsibility of those who use Linux as their environment and work tool.

Additionally, it is also your responsibility to analyze which processes are being executed and balance them, so that the processor or the Linux Kernel doesn't become overloaded.

All these points are not knowledge acquired "overnight", but are learned over time, through studying what the best Linux commands are.

With that in mind, the Certificação Linux team developed this complete content, with everything you need to know about listing processes in Linux and managing them assertively.

In this article, you will find the main Linux commands for process management and for other various functionalities.

To get all the information we've gathered, just continue reading. Check it out!

What are Linux Commands

Linux is an operating system widely used by programmers, but also by regular users for simpler activities. 

Since it is an open-source system, there are countless ways to use Linux and, therefore, there are several Linux commands.

Linux also has a series of distributions, such as Ubuntu, Fedora, Debian, Mint, and others. That way, the command list extends even further. 

Linux commands aim to facilitate the execution of actions and processes within the Linux operating system, which can be very useful for all user profiles.

Within the command line, also known as the prompt, you just need to type the command for a process you want to execute and it will immediately start.

There are basic Linux commands for all uses!

Basic Linux commands can be used for various purposes. Many people who work with IT use Ubuntu and Fedora, which are part of Linux.

That way, in order to explore all the tools that these systems have to offer, it is necessary to know basic commands.

Not only people who work with technology, but also regular users can make use of Linux.

The only thing a person who wants to optimize their processes with Linux needs to do is migrate to a command-line interface (CLI).

Most versions of Linux use the graphical user interface (GUI), which is aimed at everyday users. 

So, to use basic or advanced Linux commands, you need to learn at least how to access the CLI.

But don't worry. In this content, we've put together a complete guide so you can become an expert in Linux commands.

Understand the importance of learning Linux commands

Learning basic Linux commands is essential for improving your work, if that is the reason why you use the operating system.

The content that teaches how to use Linux more deeply is aimed at those who already know how to use shell commands, that is, those who have advanced from a simple graphical user interface. 

This means that those who understand Linux commands have greater access to operating system information.

Commands improve the work of technology professionals and still set them apart from other workers who also use the system, but in a less applied way.

Linux Commands for Process Management 

Linux commands are useful for various activities, such as process management. This is because commands can practically execute actions.

It is undeniable that, for this reason, Linux is widely used by developers, in different companies.

In addition to being an open-source operating system, Linux is versatile and built through an open community.

Do you want to start learning about Linux commands or deepen your studies? This article will help you with that!

What is a process in Linux?

Any action running on the Linux system can be classified as a process and, as such, needs to be managed.

This management only occurs through specific commands, which determine when the process will stop, go to the background, or be started.

Whoever administers Linux needs to know the commands like the back of their hand, in order to control and pause them when necessary.

It is also possible to create "layers" of process execution, placing the most important and main ones in the foreground and the others in the background.

That way, the Linux Kernel won't be overloaded and its capacity won't be impaired.

After all, some processes can be too "selfish" and end up exhausting all the processor's potential, leaving insufficient resources for the rest of the applications.

This only happens because Linux is capable of managing processes effectively, with real multiprocessing, as long as it receives the right commands.

In Linux, processes are defined by their owner, their status (whether running or paused, for example), the execution priority, and the resources they need.

Process signals in Linux

Each process in Linux stays listening for signals. These signals are used by the Kernel, by other processes, or by users to notify a specific process about a particular event.

UNIX guru W. Richard Stevens describes signals as software interrupts.

When a signal is sent to a process, it takes a specific action depending on the value that this signal carries. Each signal has a unique name and a numeric value.

Linux has over 30 defined signals. Most are used by the Kernel and some by users. Check out the most important ones, their values, and their actions:

SignalNumeric ValueAction
HUP1Hang-Up or disconnect. This signal is automatically used when you disconnect from a session or close a terminal. It is also used by server processes to invoke the rereading of the configuration file.
KILL9Unconditionally terminate the process quickly and drastically. This type of signal can leave open files and corrupt databases. It should be used if the process stops responding or in an emergency.
TERM15Terminates the process gracefully, allowing it to close files and execute its end-of-execution routines.
TSTP20Stops execution to continue later. This signal is automatically sent when we use the ctrl-z keys. It is used to put the process in the background.

Understanding signals is important to know how the system interacts with running processes.

Commands for background process control

Like other complete operating systems, Linux allows processes to run in the background.

For a process to run in the background, it must not wait for any user action, for example: waiting for a subcommand.

In this state the process will communicate with the user through signals.

Basically, to put any process in background execution, just add the "&" character at the end of the command line that will execute the process:

$ find / -name *.conf > lista_arquivos_configuracao.txt &

The find command will be executed in the background and its output will be directed to the file lista_arquivos_configuracao.txt.

1. jobs command

Usage:

$ jobs [opções]

The jobs command lists the processes running in the background. If a job number is provided the command will return information pertinent only to that specific job.

The job number is provided when the process is put in the background.

The most frequent options are:

-l Lista o PID dos processos em segundo plano.

2. bg command

Usage:

$ bg [número_da_tarefa]

The bg command puts a running process in the background. Putting the "&" signal after the command call does the same thing.

If a command is already running in the foreground, that is, attached to a terminal, we can temporarily interrupt its execution with the TSTP signal (18) by pressing the ctrl-z keys and then invoking the bg command.

3. fg command

Usage:

$ fg [número_da_tarefa]

The fg command does exactly the opposite of the bg command, bringing the task to the foreground and attaching it to a terminal.

4. nohup command

Usage:

$ nohup [command]

The nohup utility executes the specified command without attaching it to any terminal, in a way that is immune to hangups, connection drops, and intentional disconnections.

Example:

$ nohup find / -name uira* > arquivos_econtrados &

In this example nohup will execute the comando find / -name uira* command and send the output to arquivos_econtrados, which will be executed in the background.

Commands to modify execution priority

The Linux Kernel has the process scheduler as one of its critical activities.

This scheduler is a special algorithm that queues all running processes and decides which process will be executed and for how long.

The scheduler is what allows the computer to execute more than one process concurrently, dividing the CPU into execution time slices.

The implementation of the scheduler is so important that it is what really makes the difference in modern operating systems.

Linux allows the user to interfere with the execution priority of processes by releasing more or less CPU time.

The priority list can be viewed with the command ps –lax in the PRI column.

The higher the priority number, the more CPU time the process has and the more important it is. The lower the number, the less CPU time and the lower the importance.

It's possible to modify the execution priority of processes in Linux using the nice and renice commands. These commands are extremely useful in multi-user environments.

Imagine a server with many logged-in users and each one running something.

In this type of environment, it's necessary to give more or less processing slices to the various user programs to keep a stable and organized environment.

5. nice command

Usage:

$ nice [-n ajuste_de_prioridade] [comando]

The nice command adjusts the available CPU time of a process to a higher or lower priority.

In English, the word "nice" means "kind". If the priority adjustment for a process is a positive number, it means it's being kinder to other programs by lowering its priority.

If the adjustment is a negative number, it means the program is being less kind, increasing its execution priority and leaving less CPU time for other programs.

The possible priority adjustment ranges from -20 (more priority / less kind) to 19 (more kind, less priority).

If no adjustment value is passed, the nice command will set the priority to +10, decreasing the process execution time.

$ nice updatedb &

In this example the updatedb command has lower execution priority.

$ nice –n –10 folha_pagamento

In this example the folha_pagamento command will be executed with higher priority.

6. renice command

Usage:

$ renice [+/-] ajuste_prioridade [opções] PID/Usuário

The renice command adjusts the execution priority of processes that are already running. By default, the renice command takes as a parameter the PID of a specific process.

The priority adjustment is an integer number ranging from -20 (higher priority) to +20 (run anything before this process).

The most common options are:

  • -p: Receives a PID to change its priority.
  • -u: Receives a username to change the priority of all processes of that user that are running.
  • -g: Receives a group name to change the priority of all processes belonging to that group.

Example:

# renice -1 987 -u daemon root -p 32

In this example, the process with PID 987, PID 32, and all processes owned by users daemon and root will have higher priority.

Other commands for process management

There are still other commands for process management in Linux, namely:

In general, these commands are related and serve to display or make possible the visualization of running processes and their respective attributes.

7. ps command

Usage:

$ ps [opções]

The ps command generates a list of all running processes and their attributes.

The most frequent options are:

  • -a: shows the running processes of all users. Normally it only shows the processes belonging to the user who executed ps;
  • -u: shows the process list including the usernames of the process owners and execution start times, percentage of CPU used, percentage of memory used, and associated terminal;
  • -x: shows the list of processes that don't have an associated terminal. Useful for viewing server processes (daemons);
  • f: shows the processes in tree form. Very useful to identify the parent and child process relationship among running processes.

See the ps command help for more options.

8. pstree command

Usage:

$ pstree [opções]

The pstree command will show the entire process tree from init to the last running process. It's similar to the ps –auxf command.

It's useful for understanding the hierarchy of processes in Linux.

In addition to the options below, pstree can show the hierarchy belonging to a specific user or process through its PID.

  • -a: This option shows the command line used to start the processes;
  • -c: Disables the function of merging identical processes at the same hierarchy level;
  • -G: Uses the VT100 format to show the lines between processes instead of keyboard characters;
  • -h: Highlights the processes attached to the terminal at the exact moment;
  • -p: Includes the PIDs of the processes in the listing.

If you want to see running processes in a dynamic way, like Windows' "Task Manager", Linux has the top command.

9. top command

Usage:

$ top [opções]

The top command shows running processes like the ps command, but with real-time screen updates.

This feature is useful for monitoring how one or more processes behave in the system. This command also sorts the processes that use the most CPU at the top of the screen.

The most commonly used options are:

  • -b: run in batch mode or batch file. It is used to redirect the command output to another process or to a file;
  • -d n: sets the screen update interval to n seconds. The default is five seconds;
  • -n num: shows the number of times on screen the updates of running processes and then terminates. Useful to use with the –b option;
  • -q: run with real-time updates. This option should be used with caution as it can consume a large amount of CPU;
  • -u: monitor running processes of a specific user;
  • -p: monitor a specific process identified by its PID. More than one process can be defined with this option.

The top command can also support some commands that change its behavior during execution. They are:

  • Z: Change the top color scheme. For this option to be active, the terminal must support ANSI;
  • F: Add columns with more options for monitoring processes;
  • u: Show processes of a specific user;
  • k: Terminate (kill) a specific process;
  • r: Change the process execution priority (renice);
  • R: Reverse the order of processes based on CPU usage;
  • q: Quit the interactive top mode.

Now that you know how to list processes, it's time to learn how to stop running processes with the kill and killall commands.

Commands to stop running processes

If your goal is to stop one or more processes that are currently running, just try one of these commands:

  • kill command;
  • killall command;
  • pkill command;
  • or pgrep command.

They all aim to stop or terminate as many processes as needed in a direct and elegant way.

10. kill command

Usage:

$ kill [–sinal] PID

The kill command sends signals to processes. It is generally used to terminate the execution of processes identified by their PID.

If no specific signal is passed as a parameter, kill will send the TERM signal (15) to terminate the process gracefully.

11. killall command

Usage:

# killall [–sinal] NOME_DO_PROCESSO

The killall command sends signals to processes and takes as a parameter not the process PID, but its name.

It is generally used to terminate the execution of processes that have multiple child processes running at the same time.

If no specific signal is passed as a parameter, killall will send the TERM signal (15) to terminate the process gracefully.

It is important that you understand the difference between kill and killall commands. The first sends signals to one or more processes identified by PID.

The second sends signals to all processes in the execution queue that have a specific name.

The signals sent by kill and killall can be passed by name or by the corresponding integer number.

12. pkill command

Usage:

# pkill [expressão]

The pkill command is analogous to the killall command. It can send signals to processes and takes as a parameter an expression or process name.

It is generally used to terminate the execution of processes that have multiple child processes running simultaneously. $ pkill mysqld

13. pgrep command

The pgrep command is a combination of ps with grep. Usage:

# pgrep [expressão]

The pgrep command allows you to search for expressions in the list of running processes and returns the PID of the process in question.

Linux commands for system control and access

Linux commands for system control and access are all those that perform login, logout, and system switching.

Among the main commands of this type, we can mention:

  • exit: is the command that ends the session on the command line;
  • logout: is the command that terminates the session being used, but only in C shell and bash shell;
  • passwd: serves to edit the password of the logged-in user;
  • yppasswd: allows password change for the user on yellow pages;
  • rlogin: is used to log in, securely, to some Linux system;
  • slogin: performs login to Linux systems in a highly secure way;
  • ssh: serves to open a secure session, mainly on remote servers.

Linux commands for communication

Linux commands also facilitate a company's communication. By inserting some codes, it is possible to access communication channels quickly and practically. 

Listed below are the main Linux commands for communication:

  • mail: command that opens an interface for exchanging e-mails;
  • mesg: serves to allow or not the exchange of messages via terminal between active computers on the network;
  • pine: is also useful for sending and receiving e-mails;
  • talk: this command enables you to chat with other users on your network;
  • write: serves to send short messages to active users on your network. 

Main Linux commands

The main Linux commands are the simplest ones, which can be learned by beginners. 

From a command reading terminal, provided by the Linux system itself, it is possible to enter the codes correctly and thus perform actions quickly. 

We have separated a list of the main Linux commands for you:

  • nano: edits text files, notepad style;
  • watch: command responsible for scheduling the repetition of some other command;
  • script: is capable of scheduling the execution of some commands, with or without time interval;
  • cd: serves to show the directory where a file is located;
  • ls: command that displays all existing files, as well as filters them by characters;
  • rm: removes files according to the user's approval;
  • find: also serves to find files, from anywhere on the computer. 

These commands have a series of rules and subcommands for more specific execution. All this information is contained in another of our blogs. Click here to check it out! 

Linux commands for everyday use

As mentioned earlier, Linux commands help with daily activities. 

See the main Linux commands for everyday use:

Command rm

The rm command is responsible for removing files from their respective directories. 

The action can be done in different ways, according to the subcommand selected by the user. Among the options are:

  • -f: removes files without asking for permission;
  • -i: removes the file and directory;
  • -r, -R: removes the file according to the user's permission;
  • -d, -dir: removes directories that are empty. 

Command ls

The ls command displays existing files, according to a character filter. 

The filters are selected from the subcommands listed below:

  • -color=auto: separates files by color;
  • -A, -almost-all: displays files from all files, except for "." and ".." entries;
  • -a, -all: displays all files, hidden or not;
  • -m: displays files separated by comma.

Command cat

The cat command is used to open a specific file. The syntax for using it is: cat [OPTION] [FILE]. A basic example would be cat file.txt.

This command has many other functionalities, which can be accessed through the man cat command!

Command vi

The vi command works to activate a text editor with a simple interface. Basically, through it you can customize your text, edit and create new files.

To learn more about its other variations, read our blog!

Command df

The df command enables the visualization of occupied memory on the hard disk in use at the moment. 

Besides its most basic use, there are subcommands such as df -a, which displays hard disk usage and also information about fictitious systems.

Command top

The top command shows storage information of the hard disk, mainly the amount of RAM memory. 

Command cd

This command aims to show which directory a file is in or move it from one directory to another.
It is necessary to build the command according to the file you want to view. For this, enter cd [FOLDER/]. If the directory exists, it will open on your device.

Understand more about Linux processes

Besides understanding what Linux processes are, it is necessary to understand how they work.

There are several factors that we must take into consideration to understand Linux commands. 

Below, we will teach you more about the states, execution steps, and programs of Linux processes. 

Still a bit confused? Read the sequence and we will clarify all the points raised here. 

Understand the states and execution sequence of a process

After being created, the process receives a classification, also called execution state, which defines whether it will be executed immediately or later.

These classifications serve to actually prioritize executions and prevent less important processes from interfering with essential ones.

With that in mind, know that there are 4 main states of Linux processes:

  • Runnable;
  • Sleeping;
  • Stopped;
  • and Zombie.

You need to carefully know each process to manage sequences in an assertive way.

Runnable

As the name suggests, a runnable process is one that is ready to be executed instantly.

In English, "running", this process is prepared for execution and can be released without major problems, in an almost natural way.

It becomes part of the "ready queue", or ready to run, only waiting for its activation through a specific command.

Sleeping

Unlike the previous one, the sleeping process or "interruptible sleep", in English, is inactive only waiting for something to happen so it can be executed.

Literally, this process is sleeping until some command wakes it up to perform its function at the appropriate time.

Contrary to runnable processes, which we saw previously, this type of process does not consume any CPU resources and remains inactive for a determined time in another queue.

From the moment this process finishes its "sleep" time, it returns to the "ready queue".

Stopped

As the name suggests, the stopped process is literally stopped or frozen. It is not running at this moment.

The original name of this process is "stopped" or "suspended", and it is a result of the "stop" command requested by the user.

When the user issues another command, asking to resume the action ("resume"), this process returns to the waiting list or "ready queue".

Zombies

It is possible, within a process hierarchy, for a specific child process to terminate for some unexpected reason, and the parent process becomes a zombie or defunct process.

Zombie processes cannot be terminated with the kill command, because they no longer exist.

This happens because each created process receives a slot in the Kernel's process table. When it terminates, its slot in the Kernel table receives the result of its execution.

The execution result is retained in the table until someone consults it when, then, it is removed from the table.

The process state is called "zombie" when it terminates and its result has not yet been removed from the Kernel table.

Another special possibility is when any process that created new child processes running under its hierarchy terminates unexpectedly.

In this case, the child processes lose their parent process and are adopted by the init process (PID 1) which is the parent of all processes. Observe the hierarchy between processes with the command pstree –c –p.

These two situations described are not normal and may be caused by bugs in programs.

Attributes of processes (programs) in Linux

It is important that you understand that each program is at least one process and that each process has some attributes, such as:

Process ID (PID) or process identification

Each process has a unique identification number. The first init process will always have PID 1 and for the remaining processes this number is incremented as new processes are executed;

User ID and Group ID

Processes need to be executed with the privileges of a user account and the group associated with them. This is important because this is how the system can determine and manage access to resources;

Parent Process

In Linux, no process is executed independently of others. All processes in the system, with the exception of init, have a parent process responsible for its execution.

The ParentID attribute records the PID of the parent process. If the parent process terminates before the child process, the child process is "adopted" by init, gaining Parent ID equal to 1;

Environment variables

Each process inherits from the parent process some environment variables that simply store some values that may or may not be important for the running process.

It is possible that during its execution a process changes, increments, or deletes an environment variable.

A child process can inherit variables from a parent process. But a parent process cannot access variables created or changed by its children.

Working directory

Processes are also associated with a working directory, where they can read and write to disk;

Timers

The Kernel keeps records of the time when processes are created as well as the CPU time they consume during their execution.

Linux Certification: Linux courses with a fully didactic and applicable structure. Boost your career. Click and learn more!

Conclusion

Did you realize how important it is to know all the main commands to execute Linux processes?

Creating, checking, pausing, and managing processes in Linux is essential for the proper functioning of processing and the system and, in addition, for the success of your work.

Only this way is it possible to guarantee the best possible execution, in an optimized and balanced way on your Linux.

If you liked the content, you need to check out all the others already available right here, on the Blog Certificação Linux.

All articles have the same goal: to help you become an increasingly up-to-date, competent, and developed professional, capable of conquering a significant space in the job market.

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp