Команда Bash :() {:|:&};: породит процессы к смерти ядра. Можно ли объяснить синтаксис?

Вы можете использовать пакет Go os/exec для поведения, подобного подпроцессам. Например, вот тривиальная программа, которая запускает программу date в подпроцессе и сообщает о своем стандартном выводе:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}

Более интересный пример из gobyexample , который показывает, как взаимодействовать с stdio / stdout запущенных процессов:

package main

import "fmt"
import "io/ioutil"
import "os/exec"

func main() {

    // We'll start with a simple command that takes no
    // arguments or input and just prints something to
    // stdout. The `exec.Command` helper creates an object
    // to represent this external process.
    dateCmd := exec.Command("date")

    // `.Output` is another helper that handles the common
    // case of running a command, waiting for it to finish,
    // and collecting its output. If there were no errors,
    // `dateOut` will hold bytes with the date info.
    dateOut, err := dateCmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println("> date")
    fmt.Println(string(dateOut))

    // Next we'll look at a slightly more involved case
    // where we pipe data to the external process on its
    // `stdin` and collect the results from its `stdout`.
    grepCmd := exec.Command("grep", "hello")

    // Here we explicitly grab input/output pipes, start
    // the process, write some input to it, read the
    // resulting output, and finally wait for the process
    // to exit.
    grepIn, _ := grepCmd.StdinPipe()
    grepOut, _ := grepCmd.StdoutPipe()
    grepCmd.Start()
    grepIn.Write([]byte("hello grep\ngoodbye grep"))
    grepIn.Close()
    grepBytes, _ := ioutil.ReadAll(grepOut)
    grepCmd.Wait()

    // We ommited error checks in the above example, but
    // you could use the usual `if err != nil` pattern for
    // all of them. We also only collect the `StdoutPipe`
    // results, but you could collect the `StderrPipe` in
    // exactly the same way.
    fmt.Println("> grep hello")
    fmt.Println(string(grepBytes))

    // Note that when spawning commands we need to
    // provide an explicitly delineated command and
    // argument array, vs. being able to just pass in one
    // command-line string. If you want to spawn a full
    // command with a string, you can use `bash`'s `-c`
    // option:
    lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
    lsOut, err := lsCmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println("> ls -a -l -h")
    fmt.Println(string(lsOut))
}

Обратите внимание, что подпрограммы имеют мало общего с подпроцессами. Goroutines - это способ сделать несколько вещей одновременно в одном процессе Go . Тем не менее, при взаимодействии с подпроцессами часто нужны полезные процедуры, поскольку они помогают дождаться завершения подпроцессов, а также выполняют другие действия в запускающей (основной) программе. Но детали этого очень специфичны для вашего приложения.

36
задан Ciro Santilli 新疆改造中心法轮功六四事件 21 August 2014 в 20:22
поделиться

2 ответа

Это определяет функцию, вызванную :, который называет себя дважды (Код: : | :). Это делает это в фоновом режиме (&). После ; сделано функциональное определение, и функция : начинает.

Так каждый экземпляр: запускает два новых: и так далее... Как двоичное дерево процессов...

Записанный в плоскости C, которая является:

while(1) {
    fork();
}
64
ответ дан Johannes Weiss 27 November 2019 в 05:09
поделиться
:(){ :|:& };:

.. определяет функцию, названную :, который порождает себя (дважды, каждый передает по каналу в другой), и фоны сам.

С разрывами строки:

:()
{
    :|:&
};
:

Переименование эти : функция к forkbomb:

forkbomb()
{
    forkbomb | forkbomb &
};
forkbomb

можно предотвратить такие нападения при помощи ulimit для ограничения количества в расчете на пользователя процессами:

$ ulimit -u 50
$ :(){ :|:& };:
-bash: fork: Resource temporarily unavailable
$

более постоянно, можно использовать /etc/security/limits.conf (на Debian и других, по крайней мере), например:

* hard nproc 50

, Конечно, который означает, можно только выполнить 50 процессов, можно хотеть увеличить это в зависимости от того, что делает машина!

79
ответ дан dbr 27 November 2019 в 05:09
поделиться
Другие вопросы по тегам:

Похожие вопросы: