Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use FASTHTTP_PREFORK_CHILD env variable to detect child #1783

Merged
merged 1 commit into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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