Table of Contents
问题内容
解决方法
Home Backend Development Golang Node subprocess: Why doesn't .kill() close the 'go run...' process but does the direct binary?

Node subprocess: Why doesn't .kill() close the 'go run...' process but does the direct binary?

Feb 09, 2024 pm 07:10 PM

节点子进程:为什么 .kill() 不关闭“go run...”进程,但会关闭直接二进制文件?

php小编鱼仔在这篇文章中将为大家解答一个常见的问题:为什么在使用.kill()命令关闭进程时,可以关闭直接二进制文件,但无法关闭"go run..."进程?对于这个问题,我们需要了解一下节点子进程的工作原理。节点子进程是由go run命令启动的,它运行的是一个临时文件,而不是直接的二进制文件。这就导致了在使用.kill()命令关闭进程时,直接二进制文件可以被正确关闭,但临时文件却无法被关闭。本文将详细解析这个问题并给出解决方法。

问题内容

我有一个长时间运行的 go 应用程序,我想从节点进程运行它。

package main

import (
    "fmt"
    "net/http"
)

func main() {
    fmt.println("running")
    http.listenandserve(":80", nil)
}
Copy after login

我在节点中设置了我的子进程,例如:

async function application(){

    //const myprocess = exec("go run main.go"); 
    const myprocess = exec("./main"); 

    myprocess.stdout.on('data', (chunk) => {
        console.log(chunk);
    })
    
    return new promise(res => {
        settimeout(() => {
            myprocess.on("close", () => {
                console.log("close")
                res(); 
                
            }); 
            myprocess.on("exit", () => {
                console.log("exit")
            })

            myprocess.kill();
        }, 1000); 
    
    })
}
Copy after login

如果我直接运行编译的二进制文件(./main),这一切都可以正常工作。

我将得到以下输出:

running

exit
close
(process exits)
Copy after login

但是,如果我尝试使用 go run main.go 运行,我的输出是

running

exit
(process continues)
Copy after login

具体来说,这里发生了什么,go run 进程无法正常关闭?

我的理解是,这将归结为“关闭”和“退出”事件之间的区别。

来自文档:

The 'close' event is emitted after a process has ended and the stdio streams of a child process have been closed. This is distinct from the 'exit' event, since multiple processes might share the same stdio streams. The 'close' event will always emit after 'exit' was already emitted, or 'error' if the child failed to spawn.
Copy after login

好吧,那么也许 go run 让 stdio 流保持打开状态?这就是我的理解不清楚的地方。

对于我正在解决的问题,仅使用二进制文件就可以正常工作。

但是我很好奇,如果我确实想使用 go run 进程 - 我该如何正确关闭它?

在此重现:github。

解决方法

go run 命令构建可执行文件,然后在后台运行可执行文件以等待它。这意味着 go run 的进程 id 与可执行文件的 pid 不同。

您可以使用 -exec 告诉 go run 运行另一个程序(不是 go)。 例如,您可以编写run.sh

#!/bin/bash

# run executable in background
$1&

# $! is child pid
echo pid: $!

# wait for child to end
wait $!
Copy after login

然后执行 go run -exec /path/to/run.sh main.go 使用以下 main.go 尝试此操作: 包主要

import (
    "fmt"
    "os"
)

func main() {
    fmt.println(os.getpid())
}
Copy after login

得到:

$ go run -exec /tmp/run.sh /tmp/main.go
PID: 13679
13679
Copy after login

在节点代码中,您必须解析输出才能获取 pid。

The above is the detailed content of Node subprocess: Why doesn't .kill() close the 'go run...' process but does the direct binary?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go language pack import: What is the difference between underscore and without underscore? Go language pack import: What is the difference between underscore and without underscore? Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

How to implement short-term information transfer between pages in the Beego framework? How to implement short-term information transfer between pages in the Beego framework? Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How to convert MySQL query result List into a custom structure slice in Go language? How to convert MySQL query result List into a custom structure slice in Go language? Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How to write files in Go language conveniently? How to write files in Go language conveniently? Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles