What a Linux Newbie Needs to Know: Task Management. Run a process in the background in Linux Linux running a command in the background

Starting and Processing Background Processes: Job Management

You may have noticed that after you have entered the command in Terminal "e, you usually have to wait for it to complete before shell will return control to you. This means that you have run the command inpriority mode . However, there are times when this is not desirable.

Let's say, for example, that you decide to recursively copy one large directory to another. You also chose to ignore errors, so you redirected the error channel to/dev/null :

cp -R images/ /shared/ 2>/dev/null

It may take several minutes for such a command to complete. You have two solutions: the first one is brutal, meaning stopping (killing) the command, and then re-executing it, but at a more appropriate time. To do this, click ctrl+c : This will end the process and take you back to the prompt. But wait, don't do it just yet! Read on.

Let's say you want a command to run while you do something else. The solution is to start the process atbackground . To do this, click ctrl+z to pause the process:

In this case, the process will continue its work, but already as a background task, as indicated by the sign & (ampersand) at the end of the line. You will then return back to the prompt and can continue working. A process that runs as a background task, or in the background, is called a background process.task .

Of course, you can immediately start processes as background tasks by adding the sign & at the end of the command. For example, you can run the command to copy a directory in the background by typing:

cp -R images/ /shared/ 2>/dev/null &

If you wish, you can also restore this process to foreground and wait for it to complete by typingfg (Foreground - priority). To put it back into the background, enter the following sequence ctrl+z , bg .

In this way, you can run multiple jobs: each command will be assigned a job number. Team shell "a jobs displays a list of all jobs associated with the current shell "ohm. A sign is placed before the task + A that marks the last process running in the background. To restore a specific job to foreground, you can enter the commandfg , where - task number, for example,fg 5 .

Tasks and processes

Any performed in Linux program called process. Linux as a multitasking system is characterized by the fact that many processes belonging to one or more users can be running simultaneously. You can display a list of currently executing processes with the command ps, for example, as follows:

/home/larry# ps PID TT STAT TIME COMMAND 24 3 S 0:03 (bash) 161 3 R 0:00 ps /home/larry#

Note that the default command ps displays a list of only those processes that are owned by the user who launched it. To view all processes running in the system, you need to issue the command ps-a . Process numbers(process ID, or PID ) listed in the first column are unique numbers that the system assigns to each running process. The last column, titled COMMAND, indicates the name of the command that is running. In this case, the list contains processes that were started by the user larry himself. There are many other processes running in the system, full list can be viewed with the command ps-aux. However, among the commands run by the user larry , there is only bash (the shell for the user larry) and the command itself ps. It can be seen that the bash shell is running at the same time as the command ps. When the user entered the command ps, the bash shell started executing it. After the command ps has finished its work (the process table is displayed), control returns to the bash process. The bash shell then displays a prompt and waits for a new command.

A running process is also called task(job). The terms process and task are interchangeable. However, it is common to refer to a process as a task when they mean job control(job control). Job control is a command shell feature that provides the user with the ability to switch between multiple jobs.

In most cases, users will only run one task, which will be the last command they typed in the shell. However, many shells (including bash and tcsh ) have functions job management(job control), allowing you to run several commands at the same time or assignments(jobs) and, as needed, switch between them.

Job management can be useful if, for example, you are editing a large text file and want to temporarily stop editing to do something else. Using the job control functions, you can temporarily leave the editor, return to the shell prompt, and do something else. When they are done, you can return to work with the editor and find it in the same state in which it was left. There are many more useful uses for job control functions.

Foreground and background

Tasks can be either foreground(foreground), or background(background). There can only be one job in the foreground at any given time. The task in the foreground is the task you are interacting with; it receives input from the keyboard and sends the output to the screen (unless, of course, you have redirected the input or output somewhere else). In contrast, background jobs do not receive input from the terminal; as a rule, such tasks do not need interaction with the user.

Some tasks take a very long time to complete, and nothing interesting happens during their execution. An example of such tasks is compiling programs, as well as compressing large files. There is no reason to look at the screen and wait for these tasks to complete. These jobs should run in the background. During this time, you can work with other programs.

To control the execution of processes in Linux, a transfer mechanism is provided. signals. A signal is the ability of processes to exchange standard short messages directly with the system. The signal message does not contain any information, except for the signal number (for convenience, instead of the number, you can use a system-predefined name). In order to send a signal, it is enough for the process to use the system call kill(), and in order to receive a signal, nothing is needed. If a process needs to react in a special way to a signal, it can register handler, and if there is no handler, the system will respond for it. Typically, this causes the process that received the signal to terminate immediately. Signal handler starts asynchronously, immediately after receiving the signal, no matter what the process is doing at that time.

Two signals - number 9 ( KILL) and 19 ( STOP) - always processed by the system. The first one is needed in order to kill the process for sure (hence the name). Signal STOP suspends process: in this state, the process is not removed from the process table, but it is not executed until it receives a signal 18 ( CONT) - after which it will continue to work. In a Linux shell, the signal STOP can be passed to an active process using an escape sequence ctrl -Z .

Signal number 15 ( TERM) is used to interrupt the job. At interruption(interrupt) job process dies. Interruption of jobs is usually done by the control sequence ctrl -C. There is no way to restore an interrupted task. You should also be aware that some programs intercept the signal TERM(using a handler), so that pressing the key combination ctrl -C(o) may not terminate the process immediately. This is done so that the program can destroy traces of its work before it is completed. In practice, some programs cannot be interrupted in this way at all.

Transferring to the background and destroying jobs

Let's start with a simple example. Consider the yes command, which at first glance may seem useless. This command sends an endless stream of lines consisting of the character y to standard output. Let's see how this command works:

/home/larry# yes y y y y y

The sequence of such lines will continue indefinitely. You can kill this process by sending it an interrupt signal, i.e. by pressing ctrl -C. Let's do it differently now. To prevent this endless sequence from being displayed on the screen, redirect the standard output of the yes command to /dev/null . As you may know, the /dev/null device acts like a "black hole": all data sent to this device is lost. With this device it is very convenient to get rid of too abundant output of some programs.

/home/larry# yes > /dev/null

Now nothing is displayed on the screen. However, the shell prompt is also not returned. This is because the yes command is still running and sending its messages consisting of the letters y to /dev/null . You can also kill this job by sending it an abort signal.

Let's say now that you want the yes command to continue to work, but the shell prompt should also return to the screen so that you can work with other programs. To do this, you can put the yes command in the background, and it will work there without communicating with you.

One way to put a process into the background is to add an & to the end of the command. Example:

/home/larry# yes > /dev/null & + 164 /home/larry#

The message is job number(job number) for the yes process. The shell assigns a job number to each executable job. Since yes is the only job executable, it is assigned the number 1. The number 164 is the process ID number (PID ) associated with this process, and this number is also given to the process by the system. As we will see later, a process can be referred to using both of these numbers.

So now we have the yes command process running in the background, continuously sending a stream of y's to /dev/null . In order to find out the status of this process, you need to execute the command jobs, which is an internal shell command.

/home/larry# jobs + Running yes >/dev/null & /home/larry#

We see that this program really works. To check the status of a task, you can also use the command ps, as shown above.

In order to send a signal to the process (most often there is a need interrupt job operation) the utility is used kill. This command is given either a job number or a PID as an argument. An optional parameter is the number of the signal to be sent to the process. Signal sent by default TERM. In the case above, the job number was 1, so the command kill %1 will abort the job. When a job is referred to by its number (rather than PID ), then that number must be prefixed on the command line with a percent sign ("%").

Now let's enter the command jobs again to check the result of the previous action:

/home/larry# jobs Terminated yes >/dev/null

In fact, the job is destroyed, and the next time you enter the jobs command, there will be no information about it on the screen.

You can also kill a job using the process identification number (PID). This number, along with the job ID, is given when the job is started. In our example, the PID value was 164, so the command kill 164 would be equivalent to the command kill %1. When using the PID as an argument to the kill command, you do not need to enter the "%" character.

Pausing and resuming jobs

Let's start the process first with the yes command in the foreground, as we did before:

/home/larry# yes > /dev/null

As before, since the process is running in the foreground, the shell prompt is not returned to the screen.

Now instead of interrupting the task with a key combination ctrl -C, the task can suspend(suspend, literally - hang up), sending him a signal STOP. To pause the task, you must press the appropriate key combination, usually this ctrl -Z .

/home/larry# yes > /dev/null ctrl -Z+ Stopped yes >/dev/null /home/larry#

A suspended process simply does not run. It does not consume CPU resources. A suspended task can be started from the same point as if it had not been suspended.

To resume a job in the foreground, you can use the command fg(from the word foreground - foreground).

/home/larry# fg yes >/dev/null

The shell will display the name of the command again, so the user will know which task they are in. this moment launched in the foreground. Pause this task again by pressing the keys ctrl -Z, but this time we will run it in the background with the command bg(from the word background - background). This will cause the given process to work as if the command with the & character at the end was used when starting it (as was done in the previous section):

/home/larry# bg + yes $>$/dev/null & /home/larry#

This returns the shell prompt. Team now jobs should show that the process yes really works at the moment; this process can be killed with the command kill, as it was done before.

You can't use the keyboard shortcut to pause a job that's running in the background. ctrl -Z. Before suspending a task, it must be brought to the foreground with the command fg and only then stop. Thus the command fg can be applied to either suspended jobs or a job running in the background.

There is a big difference between jobs in the background and suspended jobs. The suspended task does not work - it does not consume processing power of the processor. This job does nothing. The suspended task occupies a certain amount of computer RAM, after a while the kernel will pump out this part of the memory to HDD « poste restante". On the contrary, a task in the background is running, using memory and doing some things that you may need, but you can work with other programs at the same time.

Jobs running in the background may be trying to display some text on the screen. This will interfere with work on other tasks.

/home/larry# yes &

Here, stdout has not been redirected to /dev/null , so an endless stream of y characters will be printed to the screen. This thread cannot be stopped because the key combination ctrl -C does not affect jobs in the background. In order to stop this issuance, you need to use the command fg, which will bring the task to the foreground, and then kill the task with a key combination ctrl -C .

Let's make one more remark. Usually a team fg and team bg affect the jobs that were last paused (these jobs will be marked with a + symbol next to the job number if you enter the command jobs). If one or more jobs are running at the same time, jobs can be placed in the foreground or in the background by giving command arguments fg or commands bg their identification number (job ID). For example, the command fg %2 puts job number 2 in the foreground, and the command bg %3 puts job number 3 in the background. Use PID as command arguments fg and bg it is forbidden.

Moreover, to bring a job to the foreground, you can simply specify its number. Yes, the team %2 will be equivalent to the command fg %2 .

It is important to remember that the job control function belongs to the shell. Teams fg , bg and jobs are internal shell commands. If, for some reason, you are using a shell that does not support job control functions, then you will not find these (and similar) commands in it.

Last time we talked about working with input, output, and error streams in bash scripts, about file descriptors, and about stream redirection. Now you already know enough to write something of your own. At this stage of learning bash, you may well have questions about how to manage running scripts, how to automate their launch.

So far, we've been typing script names into the command line and hitting Enter, which will cause programs to run immediately, but that's not the only way to invoke scripts. Today we will talk about how a script can work with Linux signals, about different approaches to running scripts and managing them at runtime.

Linux Signals

In Linux, there are more than three dozen signals that are generated by the system or applications. Here is a list of the most commonly used ones that will surely come in handy when developing scripts command line.
Signal code
Name
Description
1
SIGHUP
Terminal closure
2
SIGINT
Signal to stop the process by the user from the terminal (CTRL + C)
3
SIGQUIT
Signal to stop the process by the user from the terminal (CTRL + \) with a memory dump
9
SIGKILL
Terminating a Process Unconditionally
15
SIGTERM
Process termination request signal
17
SIGSTOP
Forced suspension of the execution of the process, but not the termination of its work
18
SIGTSTP
Pausing process from terminal (CTRL+Z) but not shutting down
19
SIGCONT
Resuming a previously stopped process

If the bash shell receives a SIGHUP signal when you close the terminal, it exits. Before exiting, it sends a SIGHUP signal to all processes running in it, including running scripts.

The SIGINT signal causes the operation to stop temporarily. The Linux kernel stops allocating processor time to the shell. When this happens, the shell notifies the processes by sending them a SIGINT signal.

Bash scripts have no control over these signals, but they can recognize them and execute commands to prepare the script for the consequences of the signals.

Sending signals to scripts

The bash shell allows you to send signals to scripts using keyboard shortcuts. This comes in very handy if you need to temporarily stop a running script or exit it.

Terminating a process

The CTRL + C key combination generates a SIGINT signal and sends it to all processes running in the shell, which causes them to terminate.

Run the following command in the shell:

$ sleep 100
After that, we will complete its work with the key combination CTRL + C.


Ending a process from the keyboard

Temporarily stop the process

The CTRL + Z key combination generates the SIGTSTP signal, which suspends the process but does not terminate its execution. Such a process remains in memory, its work can be resumed. Run the command in the shell:

$ sleep 100
And temporarily stop it with the key combination CTRL + Z.


Suspending a process

The number in square brackets is the job number that the shell assigns to the process. The shell treats the processes running in it as jobs with unique numbers. The first process is assigned the number 1, the second - 2, and so on.

If you suspend a shell-bound job and try to exit it, bash will issue a warning.

You can view suspended jobs with the following command:

Ps–l


Task list

In the S column, which displays the state of the process, T is displayed for suspended processes. This indicates that the command is either paused or in a trace state.

If you need to end a suspended process, you can use the kill command. Details about it can be read.

Her call looks like this:

Kill processID

Interception of signals

To enable Linux signal tracing in a script, use the trap command. If the script receives the signal specified when calling this command, it handles it on its own, while the shell will not process such a signal.

The trap command allows the script to respond to signals, otherwise they are processed by the shell without its participation.

Let's look at an example that shows how the trap command specifies the code to execute and a space-separated list of signals we want to trap. In this case, this is just one signal:

#!/bin/bash trap "echo " Trapped Ctrl-C"" SIGINT echo This is a test script count=1 while [ $count -le 10 ] do echo "Loop #$count" sleep 1 count=$(($ count + 1)) done
The trap command used in this example prints out a text message whenever it encounters a SIGINT signal, which can be generated by pressing Ctrl + C on the keyboard.


Interception of signals

Each time you press CTRL + C , the script executes the echo command specified when calling trace instead of letting the shell exit.

You can catch the exit signal from a script by using the name of the EXIT signal when calling the trap command:

#!/bin/bash trap "echo Goodbye..." EXIT count=1 while [ $count -le 5 ] do echo "Loop #$count" sleep 1 count=$(($count + 1)) done


Intercepting the exit signal from the script

When a script exits, whether it is a normal exit or an exit caused by the SIGINT signal, a hook will be triggered and the shell will execute the echo command.

Modification of intercepted signals and cancellation of interception

To modify the signals intercepted by the script, you can execute the trap command with new parameters:

#!/bin/bash trap "echo "Ctrl-C is trapped."" SIGINT count=1 while [ $count -le 5 ] do echo "Loop #$count" sleep 1 count=$(($count + 1) ) done trap "echo " I modified the trap!"" SIGINT count=1 while [ $count -le 5 ] do echo "Second Loop #$count" sleep 1 count=$(($count + 1)) done


Modification of signal interception

After the modification, the signals will be processed in a new way.

Trapping signals can also be canceled, for this it is enough to execute the trap command, passing it a double dash and the name of the signal:

#!/bin/bash trap "echo "Ctrl-C is trapped."" SIGINT count=1 while [ $count -le 5 ] do echo "Loop #$count" sleep 1 count=$(($count + 1) ) done trap -- SIGINT echo "I just removed the trap" count=1 while [ $count -le 5 ] do echo "Second Loop #$count" sleep 1 count=$(($count + 1)) done
If the script receives a signal before canceling the trap, it will process it as specified in the actual trap command. Let's run the script:

$ ./myscript
And press CTRL + C on the keyboard.


Signal intercepted before the interception was canceled

The first CTRL + C was pressed at the time of the script execution, when the signal interception was in effect, so the script executed the echo command assigned to the signal. After execution reached the command to cancel the interception, the CTRL + C command worked in the usual way, terminating the script.

Running command line scripts in the background

Sometimes bash scripts take a long time to complete a task. However, you may need to be able to work normally on the command line without waiting for the script to complete. Implementing this is not so difficult.

If you have seen the list of processes displayed by the ps command, you may have noticed processes that run in the background and are not attached to a terminal.
Let's write the following script:

#!/bin/bash count=1 while [ $count -le 10 ] do sleep 1 count=$(($count + 1)) done
Run it by adding an ampersand (&) after the name:

$ ./myscript &
This will cause it to run as a background process.


Running a script in the background

The script will be run in a background process, its identifier will be displayed in the terminal, and when its execution is completed, you will see a message about it.

Note that although the script is running in the background, it continues to use the terminal to print messages to STDOUT and STDERR , meaning that its output text or error messages can be seen in the terminal.


List of processes

With this approach, if you exit the terminal, the script running in the background will also exit.

What if you want the script to continue running even after you close the terminal?

Executing scripts that don't exit when the terminal is closed

Scripts can be executed in background processes even after leaving the terminal session. To do this, you can use the nohup command. This command allows you to run a program by blocking SIGHUP signals sent to the process. As a result, the process will be executed even when exiting the terminal in which it was launched.

Let's apply this technique when running our script:

Nohup ./myscript &
This is what will be output to the terminal.


noup command

The nohup command unbinds a process from the terminal. This means that the process will lose references to STDOUT and STDERR . In order not to lose the data output by the script, nohup automatically redirects messages coming to STDOUT and STDERR to the nohup.out file.

Note that when running multiple scripts from the same directory, their output will end up in one nohup.out file.

Viewing Jobs

The jobs command allows you to view the current jobs that are running in the shell. Let's write the following script:

#!/bin/bash count=1 while [ $count -le 10 ] do echo "Loop #$count" sleep 10 count=$(($count + 1)) done
Let's run it:

$ ./myscript
And temporarily stop with the key combination CTRL + Z.


Running and pausing a script

Let's run the same script in the background, while redirecting the output of the script to a file so that it does not display anything on the screen:

$ ./myscript > outfile &
If we now run the jobs command, we will see information about both the paused script and the one that is running in the background.


Getting information about scripts

The -l option when calling the jobs command indicates that we need information about the process IDs.

Restarting suspended jobs

In order to restart the script in the background, you can use the bg command.

Let's run the script:

$ ./myscript
Let's press CTRL + Z , which will temporarily stop its execution. Let's execute the following command:

$bg


bg command

The script is now running in the background.

If you have multiple suspended jobs, you can pass a job number to the bg command to restart a particular job.

To restart the job in normal mode, use the fg command:

Scheduling scripts to run

Linux provides a couple of ways to run bash scripts at a given time. These are the at command and the cron job scheduler.

The at command looks like this:

At [-f filename] time
This command recognizes many time formats.

  • Standard, indicating hours and minutes, for example - 10:15.
  • Using AM/PM indicators, before or after noon, for example - 10:15PM.
  • Using special names like now , noon , midnight .
In addition to being able to specify the start time for a job, you can also pass a date to the at command using one of its supported formats.
  • A standard date format that uses the patterns MMDDYY , MM/DD/YY , or DD.MM.YY .
  • A textual representation of the date, such as Jul 4 or Dec 25 , with or without the year.
  • An entry like now + 25 minutes .
  • An entry like 10:15PM tomorrow .
  • Recording like 10:15 + 7 days .
We will not delve into this topic, consider a simple use case for the command:

$ at -f ./myscript now


Job scheduling using the at command

The -M switch when calling at is used to send what the script outputs to e-mail if the system is configured accordingly. If sending an email is not possible, this switch will simply suppress the output.

You can use the atq command to list the pending jobs:


List of pending jobs

Deleting pending jobs

You can use the atrm command to remove a pending job. When it is called, the task number is indicated:

$ atrm 18


Deleting a Job

Running scripts on a schedule

Scheduling scripts to run once using the at command can make life easier in many situations. But what if you want the script to run at the same time every day, or once a week, or once a month?

Linux has a crontab utility that allows you to schedule scripts to run on a regular basis.

Crontab runs in the background and, based on the data in the so-called cron tables, runs scheduled jobs.

To view the existing table of cron jobs, use the following command:

$ crontab -l
When scheduling a script to run, crontab accepts when the job needs to run, in this format:

Minute, hour, day of the month, month, day of the week.
For example, if you want a certain script called command to be executed every day at 10:30, this would correspond to the following entry in the task table:

30 10 * * * command
Here, the wildcard "*" used for the fields specifying the day of the month, month, and day of the week indicates that cron should run the command every day of every month at 10:30.

If, for example, you want the script to run at 4:30PM every Monday, you would need to create an entry in the jobs table like this:

30 16 * * 1 command
Days of the week are numbered starting from 0, 0 means Sunday, 6 means Saturday. Here is another example. Here the command will be executed at 12 noon on the first day of every month.

00 12 1 * * command
Months are numbered starting from 1.
In order to add an entry to the table, you need to call crontab with the -e switch:

Crontab -e
Then you can enter commands for generating the schedule:

30 10 * * * /home/likegeeks/Desktop/myscript
Thanks to this command, the script will be called daily at 10:30. If you encounter the "Resource temporarily unavailable" error, run the following command as root:

$ rm -f /var/run/crond.pid
Organizing the periodic launch of scripts using cron can be even easier by using a few special directories:

/etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly
Putting a script file in one of them will cause it to run hourly, daily, weekly, or monthly, respectively.

Running scripts on login and on shell startup

You can automate the launch of scripts based on various events, such as user login or shell launch. you can read about the files that are processed in such situations. For example, these are the following files:

$HOME/.bash_profile $HOME/.bash_login $HOME/.profile
To run a script on login, place the script call in the .bash_profile file.

What about running scripts when opening a terminal? The .bashrc file will help organize this.

Results

Today we discussed issues related to managing the life cycle of scripts, talked about how to run scripts in the background, how to schedule their execution on a schedule. Next time read about functions in bash scripts and library development.

Dear readers! Do you use scheduling tools to run command-line scripts? If yes, please tell us about them.

Like any other multitasking system, Linux runs multiple processes at the same time. In general, I will not mislead you, because a normal single-processor computer can only perform one task at a given time, which is why Linux queues processes for execution.

There are several basic commands for managing processes

  • ps- display a list of running processes
  • kill- sends a signal to one or more processes (mostly to "kill" them)
  • jobs- an alternative way to view the processes you are running
  • bg- puts the execution of the process in the background
  • fg- Brings the process out of the background

Although it may seem that this knowledge is rather abstract, it can be of practical use even for the average user who uses a graphical interface. You may not know yet that most graphic programs(if not all) can be run using the command line. For example, let's try to launch a browser, I think most linux-oids have either Google Chrome or Firefox

[email protected]:/home/pub/www/vv$ google-chrome Created new window in existing browser session.

You can specify the URL you want to open

[email protected]:/home/pub/www/vv$ google-chrome http://website Created new window in existing browser session.

I already have Chrome running through the graphical interface, so the browser reports that a new window is being created in the existing session and gives control to the command line. Or, for example, if you need to open a graphic file manager as root (example will work for Gnome GUI with Nautilus installed)

[email protected]:/home/pub/www/vv$ sudo nautilus /root/ password for enej:

Since the process was not started in the background, you can no longer perform any actions in this terminal window (you can press CTRL + C to end the process).

Background mode

In order to make life easier, when running graphical programs or processes that can run for a long time, they are usually put into the background, for example, let's run the browser in the background

[email protected]:/home/pub/www/vv$ google-chrome http://website&9248

Ampersant sign ( & ) at the end of the command call means that the process should be placed in the background. In this case, it remains possible to work with this terminal window.

But suddenly you forgot to put an ampresant at the end of the call, then there is another way. You must first stop the execution by pressing CTRL + Z, then we get command line control and we can call the command bg, which will put the last running process in the background. Said by example

[email protected]:/home/pub/www/vv$ google-chrome http://site ^Z + Stopped google-chrome http://site [email protected]:/home/pub/www/vv$ bg + google-chrome http://website&

Team fg brings the last running process out of the background.

List of running processes

Since you now know how to put commands in the background, it was good to see a list of them. For this, the command is used jobs or more powerful ps

[email protected]:/home/pub/www/vv$ jobs - Running nm-applet & (wd: ~/bin) + Running google-chrome http://website & [email protected]:/home/pub/www/vv$ ps PID TTY TIME CMD 2304 pts/0 00:00:02 bash 11104 pts/0 00:00:01 chrome 11108 pts/0 00:00:00 chrome 11110 pts/0 00 :00:00 chrome 11132 pts/0 00:00:00 chrome 12088 pts/0 00:00:00 ps 21165 pts/0 00:00:27 nm-applet

How to "kill" a process?

If the process stops responding (i.e., hangs), it must be forcibly "killed". I think those who use FireFox have come across this. For such tasks, use the command kill. But first you need to somehow define the process. For this you can use the command jobs or ps. With the help of the first you can find out the process number, with the help of the second its ID.

[email protected]:/home/pub/www/vv$ google-chrome http://freaksidea..com & 15181 [email protected]:/home/pub/www/vv$ ps PID TTY TIME CMD 2304 pts/0 00:00:02 bash 15181 pts/0 00:00:00 chrome 15238 pts/0 00:00:00 ps 21165 pts/0 00 :00:27 nm-applet [email protected]:/home/pub/www/vv$ kill 15181

Teams fg and bg as the first argument, they can take the number of the running process, for its subsequent input / output to / from the background.

More about kill

Actually the team kill used to send different signals to processes. It's just that in most cases this signal tells the command that it should exit. If programs are written correctly, they listen for various signals from the operating system and respond to them. For example, a text editor should listen for any signal that notifies users that the user is logged out or that the computer is shutting down. When he (the text editor) "heard" such a signal, he must save the open documents before finishing his work. Team kill can send several types of signals, to find out which ones, enter kill -l. Below is a list of the most commonly used signals (the number in brackets is the signal number)

  • SIGNUP(1)- was originally intended to inform the program about the loss of communication with the control terminal (terminals were often connected to the system using modems, so the name of the signal comes from hung up - hang up). The SIGHUP signal is also sent to the application if the process leader of the session has finished its work. Many daemons that do not have a session leader handle this signal in the same way. In response to receiving a SIGHUP, the daemon is usually restarted (or simply re-reads the configuration file). By default, the program that receives this signal terminates.
  • SIGINT(2)- usually sent to a process if the terminal user has given a command to terminate the process (usually this command is the keyboard shortcut Ctrl + C)
  • SIGTERM(15)- Causes a "polite" termination of the program. Having received this signal, the program can perform the necessary operations before the completion (for example, save open documents). Receiving SIGTERM does not indicate an error in the program, but the desire of the OS or the user to terminate it.
  • SIGKILL(9)- Causes a forced termination of the program. The program can neither process nor ignore this signal.

Default command kill sends SIGTERM signal, but you can also specify the signal number or its name. Let's say that your Chrome freezes (sometimes my flash player stops working adequately)

[email protected]:/home/pub/www/vv$ google-chrome http://website&22066 [email protected]:/home/pub/www/vv$ jobs - Running nm-applet & (wd: ~/bin) + Running google-chrome http://website & [email protected]:/home/pub/www/vv$ kill -SIGTERM %2 [email protected]:/home/pub/www/vv$ kill -SIGKILL %2 [email protected]:/home/pub/www/vv$ kill -9 %2

P.S.: I think 2 teams will be very interesting for beginners: notify-send(sends a message through the graphical shell, in Gnome appears at the top right) and espeak(speech synthesizer). If you do not have one of them, you can install it using the command apt-get

[email protected]:/home/pub/www/vv$ sudo apt-get install espeak notify-send

The Linux terminal service runs in single-tasking mode by default. This means that any running brigade blocks the terminal until it is completed. This approach is not convenient when running programs that require a long execution time. This problem can be solved in two ways: open an additional terminal window and execute another command in it, or use the background mode. All current Operating Systems, including Linux, are multitasking, which implies the possibility of synchronous execution of many programs.

How can I run a brigade in the background so that I can immediately access the command line interface? A brigade that has been forced to run is called a background process. Background processes are not shown on the screen. For example, the Apache HTTPD server runs in the background to serve web pages. You can put a shell script or any command in low priority mode. A task (for example, a team or a script) can be placed in the background by adding the "&" character to the end of the command line. This statement puts the command in the background and frees up space in the terminal. A brigade that runs in the background is called a job. While the background command is running, it is possible to execute any other commands. The syntax looks like this:

command & script-name & /path/to/command arg1 arg2 & command-1 | command-2 arg1 & command-1 | command-2 -arg1 -arg2 >/path/to/output &

To run programs in the background that does not block the terminal window, you must use the special "&" instructor. Place this character at the very end of the line after the command name, options, and input parameters. In general, this sequence can be entered as "command_name -option incoming_parameter &".

ls ~/* > ~/test-file.txt &
18960

After pressing the Enter button, the program will automatically run in the background. In this case, the terminal will show a line with the following content "[task_number] process_id", and will issue an invitation to enter the newly minted command.

Find Commands Running in the Background in Linux

Run the following command:

Data output example:

Running find / -iname "*.c" 2> /dev/null > /tmp/output.txt &
+ Running grep -R "hostNamed" / 2> /dev/null > /tmp/grep.txt &

Where and order IDs.

To display process IDs for job IDs in addition to the standard casts, pass the -l option:

Data output example:

7307 Running find / -iname "*.c" 2> /dev/null > /tmp/output.txt &
+ 7324 Running grep -R "hostNamed" / 2> /dev/null > /tmp/grep.txt &

To display only process IDs, type:

Data output example:

Stop executing commands running in the background

To force or gracefully terminate a process, use the kill command. The syntax looks like this:

kill PID
kill -15 PID
kill -9 PID
killall process-Name-Here
killall -15 process-Name-Here
killall -9 process-Name-Here

Reverting a program to foreground in Linux

Linux allows not only to run programs in the background, but also to return to the usual execution at will. There are two tools for this: the command ( Team - a group of people united by common motives, interests) fg and the % operator. The principle of their efforts is extremely simple. fg requires you to specify the job number as a parameter, and to % it must be substituted immediately after the operator without spaces.

find / -name .ini 2> ~/results.txt &
19090
fg 1
bash: fg: task ended
+ Exit from 1 find / -name .ini 2> ~/results.txt