Linux recursive classic: fork bomb

Source: Internet
Author: User
A function is a very important concept in programming. It can divide programs into code blocks with relatively independent functions, so that the code is more modular and the structure is clearer, and can effectively reduce the amount of code in the program. Recursive functions fully reflect these advantages. By calling itself in the function definition, you can turn complex computing problems into a simple

A function is a very important concept in programming. It can divide programs into code blocks with relatively independent functions, so that the code is more modular and the structure is clearer, and can effectively reduce the amount of code in the program. Recursive functions fully reflect these advantages. By calling itself in the function definition, you can turn complex computing problems into a simple iterative algorithm. When backtracking to boundary conditions, return the previous function layer by layer. There are many mathematical problems that are very suitable for designing program solutions using recursive ideas, such as factorial and hanoi Tower.

Many people may have heard of the fork bomb. It is actually a very simple recursive program, and the program does only the same thing: continuously fork a new process. Because the program is recursive, without any restrictions, this will cause the simple program to quickly exhaust all the resources in the system.

Designing such a fork bomb in bash is very simple. Jaromil designed the most streamlined implementation of a fork bomb in 2002. The entire program, from function definition to calling, contains only 13 characters, as shown in Listing 1.

Listing 1. fork bomb in bash
. () {. | .&};.



At first glance, this string of characters cannot be seen at all. Let's explain one by one what it is doing. For ease of interpretation, we reset the format of the content in Listing 1 and add a row number to the front, as shown in Listing 2.

Listing 2. Interpretation of the fork bomb in bash
1 .()
2 {
3. | .&
4}
5;
6.


The following section defines a function named decimal point. There is no optional parameter.
Row 2nd indicates that the function body starts.
The first line is what the function body really wants to do. First, it recursively calls the function and then uses the pipeline to call a new process (what it wants to do is to call the function recursively ), and put it in the background for execution.
Row 4th indicates that the function body ends.
Row 5th does not perform any operations.CommandTo separate two commands. In general, it indicates that this program contains two parts. First, a function is defined and then called.
Row 6th indicates that this function is called.

You may be confused about the function name. Can the decimal point be used as the function name? After all, the decimal point is an embedded shell command used to read the specified file in the Current shell environment and run the command. Actually, this depends on the order in which bash interprets commands. By default, bash is in non-POSIX mode. The order of command interpretation is as follows:
Keywords, such as if and.
Alias. Aliases cannot be the same as keywords, but can be defined for keywords, such as end = fi.
Special embedded commands, such as break and continue. Special embedded commands defined by POSIX include:. (decimal point), :( colon), break, continue,Eval,ExEc, exit,Export, Readonly, return,Set, Shift,TimeS,TrAp andUnset. Bash adds a special embedded command source.
Function. If it is in non-POSIX mode, bash will first match the function and then match the embedded command.
Non-special embedded commands, suchCdAnd test.
Scripts and executable programs. Search in the directory specified by the PATH environment variable and return the first match.

By default, bash is in non-POSIX mode, so the decimal point in the fork bomb takes precedence as a function for matching. (In fact, the original design of Jaromil does not use the decimal point, but uses a colon, which can also achieve the same effect .) To run the bash script in POSIX mode, you can use the following three methods:
Use the -- posix option to start bash.
After bash is run, run the set-o posix command.
Use/bin/sh.

The last method is interesting. Although sh is a symbolic link to bash in most systems, it is enabled in POSIX mode, and all behaviors fully comply with POSIX specifications. In the example given in listing 3, we can find that the decimal point is interpreted as a function in the default bash and can be executed normally. But in sh, the decimal point is treated as an embedded command, therefore, when a function is called, it is considered that a syntax error exists and cannot be executed normally.

Listing 3. Differences between bash and sh in command matching order
[Root @ localhost ~] #Ls-L/bin/bash/bin/sh
-Rwxr-xr-x 1 root 735144/bin/bash
Lrwxrwxrwx 1 root 4/bin/sh-> bash
[Root @ localhost ~] # Echo $ SHELL
/Bin/bash
[Root @ localhost ~] #. () {Echo hello ;};.
Hello
[Root @ localhost ~] # Sh
Sh-3.2 # echo $ SHELL
/Bin/bash
Sh-3.2 #. () {echo hello ;};.
Sh: '.': not a valIdIdentifier
Sh :.:FileName argument requirEd
.: Usage:. filename [arguments]
Sh-3.2 #



Once the fork bomb in Listing 1 is run, new processes will continuously generate at an exponential power of 2, which will cause rapid consumption of system resources, unless the machine is restarted, otherwise, there is basically no way. To prevent this from causing too much damage, we can useUlimitLimit the number of processes that each user can create, as shown in Listing 4.

Listing 4. Limiting the number of processes that a user can create
[Root @ localhost ~] # Ulimit-u 128
[Root @ localhost ~] # Ulimit-
Core file size (blocks,-c) 0
Data seg size (kbytes,-d) unlimited
Max nice (-e) 20
File size (blocks,-f) unlimited
Pending signals (-I) unlimited
Max locked memory (kbytes,-l) unlimited
Max memory size (kbytes,-m) unlimited
Open File (-n) 1024
Pipe size (512 bytes,-p) 8
POSIX message queues (bytes,-q) unlimited
Max rt priority (-r) unlimited
Stack size (kbytes,-s) 8192
CpU time (seconds,-t) unlimited
Max user processes (-u) 128
Virtual memory (kbytes,-v) unlimited
File locks (-x) unlimited
[Root @ localhost ~] #. () {. | .&};.
[1] 6152
[Root @ localhost ~] # Bash: fork: Resource temporarily unavailable
Bash: fork: Resource temporarily unavailable
Bash: fork: Resource temporarily unavailable
...



In Listing 4, we limit the maximum number of processes that a user can create to 128. Executing the fork bomb will quickly fork a large number of processes and will not be able to continue execution due to insufficient resources.

The fork bomb made us realize the powerful functions of recursive functions, and also realized that the damage caused by recursive functions will be huge once used improperly. In fact, the fork bomb is just a very simple recursive function. It does not involve parameter passing, return values, and other issues. Are these problems fully supported when using bash programming? Next, let's use several examples to illustrate the issues that should be paid attention to when writing recursive functions in bash.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.