Skip to content

Commit

Permalink
Use FASTHTTP_PREFORK_CHILD env variable to detect child (#1783)
Browse files Browse the repository at this point in the history
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: #1782
  • Loading branch information
erikdubbelboer authored Jun 2, 2024
1 parent 3edfab8 commit b001a40
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
22 changes: 5 additions & 17 deletions prefork/prefork.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package prefork

import (
"errors"
"flag"
"log"
"net"
"os"
Expand All @@ -14,8 +13,8 @@ import (
)

const (
preforkChildFlag = "-prefork-child"
defaultNetwork = "tcp4"
preforkChildEnvVariable = "FASTHTTP_PREFORK_CHILD"
defaultNetwork = "tcp4"
)

var (
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions prefork/prefork_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit b001a40

Please sign in to comment.