испольнение процессов

This commit is contained in:
badkaktus 2019-10-12 21:55:39 +03:00
parent f411479c93
commit 653625e88a
3 changed files with 29 additions and 30 deletions

View File

@ -69,6 +69,6 @@ Epoch
HTTP клиенты (HTTP Clients) HTTP клиенты (HTTP Clients)
HTTP серверы (HTTP Servers) HTTP серверы (HTTP Servers)
Порождающие процессы (Spawning Processes) Порождающие процессы (Spawning Processes)
Exec'ing Processes Исполняющие процессы (Exec'ing Processes)
Signals Signals
Exit Exit

View File

@ -1,12 +1,11 @@
// In the previous example we looked at // В предыдущем примере мы рассмотрели [порождение внешних
// [spawning external processes](spawning-processes). We // процессов](spawning-processes). Мы делаем это,
// do this when we need an external process accessible to // когда нам нужен внешний процесс, доступный для
// a running Go process. Sometimes we just want to // запущенного процесса Go. Иногда мы просто хотим
// completely replace the current Go process with another // полностью заменить текущий процесс Go другим
// (perhaps non-Go) one. To do this we'll use Go's // (возможно, не Go). Для этого мы будем использовать
// implementation of the classic // реализацию Go-имплементацию классической функции
// <a href="http://en.wikipedia.org/wiki/Exec_(operating_system)"><code>exec</code></a> // <a href="http://en.wikipedia.org/wiki/Exec_(operating_system)"><code>exec</code></a>.
// function.
package main package main
@ -18,31 +17,30 @@ import (
func main() { func main() {
// For our example we'll exec `ls`. Go requires an // Для нашего примера мы выполним `ls`. Go требует
// absolute path to the binary we want to execute, so // абсолютного пути к двоичному файлу, который мы
// we'll use `exec.LookPath` to find it (probably // хотим выполнить, поэтому мы используем `exec.LookPath`,
// `/bin/ls`). // чтобы найти его (вероятно, `/bin/ls`).
binary, lookErr := exec.LookPath("ls") binary, lookErr := exec.LookPath("ls")
if lookErr != nil { if lookErr != nil {
panic(lookErr) panic(lookErr)
} }
// `Exec` requires arguments in slice form (as // `Exec` требует аргументы в форме среза
// apposed to one big string). We'll give `ls` a few // (в сочетании с одной большой строкой). Мы используем в `ls`
// common arguments. Note that the first argument should // несколько общих аргументов. Обратите внимание, что
// be the program name. // первым аргументом должно быть имя программы.
args := []string{"ls", "-a", "-l", "-h"} args := []string{"ls", "-a", "-l", "-h"}
// `Exec` also needs a set of [environment variables](environment-variables) // `Exec` также нужен набор [переменных среды](environment-variables)
// to use. Here we just provide our current // для использования. Здесь мы просто предоставляем
// environment. // нашу текущую среду.
env := os.Environ() env := os.Environ()
// Here's the actual `syscall.Exec` call. If this call is // Вот фактический вызов `syscall.Exec`. Если этот вызов
// successful, the execution of our process will end // будет успешным, выполнение нашего процесса на этом
// here and be replaced by the `/bin/ls -a -l -h` // закончится и будет заменено процессом `/bin/ls -a -l -h`.
// process. If there is an error we'll get a return // В случае ошибки мы получим возвращаемое значение.
// value.
execErr := syscall.Exec(binary, args, env) execErr := syscall.Exec(binary, args, env)
if execErr != nil { if execErr != nil {
panic(execErr) panic(execErr)

View File

@ -5,7 +5,8 @@ drwxr-xr-x 4 mark 136B Oct 3 16:29 .
drwxr-xr-x 91 mark 3.0K Oct 3 12:50 .. drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
-rw-r--r-- 1 mark 1.3K Oct 3 16:28 execing-processes.go -rw-r--r-- 1 mark 1.3K Oct 3 16:28 execing-processes.go
# Note that Go does not offer a classic Unix `fork` # Обратите внимание, что Go не предлагает классическую
# function. Usually this isn't an issue though, since # Unix функцию `форка`. Обычно это не проблема,
# starting goroutines, spawning processes, and exec'ing # так как запуск горутин, порождение процессов и
# processes covers most use cases for `fork`. # выполнение процессов покрывают большинство случаев
# использования `форка`.