From b001a40bea55b9be4c525375e01eaca5a85223db Mon Sep 17 00:00:00 2001 From: Erik Dubbelboer Date: Sun, 2 Jun 2024 10:33:50 +0200 Subject: [PATCH] Use FASTHTTP_PREFORK_CHILD env variable to detect child (#1783) It's better to use an environment variable as they are more standard. They way flags are parsed isn't standardized within the Go ecosystem. Fixes: https://github.com/valyala/fasthttp/issues/1782 --- prefork/prefork.go | 22 +++++----------------- prefork/prefork_test.go | 4 ++-- 2 files changed, 7 insertions(+), 19 deletions(-) diff --git a/prefork/prefork.go b/prefork/prefork.go index d40bded1a7..11672bbee5 100644 --- a/prefork/prefork.go +++ b/prefork/prefork.go @@ -2,7 +2,6 @@ package prefork import ( "errors" - "flag" "log" "net" "os" @@ -14,8 +13,8 @@ import ( ) const ( - preforkChildFlag = "-prefork-child" - defaultNetwork = "tcp4" + preforkChildEnvVariable = "FASTHTTP_PREFORK_CHILD" + defaultNetwork = "tcp4" ) var ( @@ -69,21 +68,9 @@ type Prefork struct { files []*os.File } -func init() { //nolint:gochecknoinits - // Definition flag to not break the program when the user adds their own flags - // and runs `flag.Parse()` - flag.Bool(preforkChildFlag[1:], false, "Is a child process") -} - // IsChild checks if the current thread/process is a child. func IsChild() bool { - for _, arg := range os.Args[1:] { - if arg == preforkChildFlag { - return true - } - } - - return false + return os.Getenv(preforkChildEnvVariable) == "1" } // New wraps the fasthttp server to run with preforked processes. @@ -148,9 +135,10 @@ func (p *Prefork) setTCPListenerFiles(addr string) error { func (p *Prefork) doCommand() (*exec.Cmd, error) { /* #nosec G204 */ - cmd := exec.Command(os.Args[0], append(os.Args[1:], preforkChildFlag)...) + cmd := exec.Command(os.Args[0], os.Args[1:]...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr + cmd.Env = append(os.Environ(), preforkChildEnvVariable+"=1") cmd.ExtraFiles = p.files err := cmd.Start() return cmd, err diff --git a/prefork/prefork_test.go b/prefork/prefork_test.go index c7339c564f..81a4e64ac2 100644 --- a/prefork/prefork_test.go +++ b/prefork/prefork_test.go @@ -13,11 +13,11 @@ import ( ) func setUp() { - os.Args = append(os.Args, preforkChildFlag) + os.Setenv(preforkChildEnvVariable, "1") } func tearDown() { - os.Args = os.Args[:len(os.Args)-1] + os.Unsetenv(preforkChildEnvVariable) } func getAddr() string {