Skip to content

Commit 3677f97

Browse files
committed
feat: add refork
1 parent 02538d9 commit 3677f97

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

fork.go

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,11 @@ type Function struct {
3838
// NewFork createas and initializes a Fork
3939
// A Fork object can be manipluated to control how a process is launched.
4040
// E.g. you can set new namespaces in the SysProcAttr property...
41-
// or, you can set custom args with the (optional) variatic args aparameters.
42-
// If you set args, the first should be the program name (Args[0]), which may
43-
// Which may or may not match the executable.
41+
//
42+
// or, you can set custom args with the (optional) variatic args aparameters.
43+
// If you set args, the first should be the program name (Args[0]), which may
44+
// Which may or may not match the executable.
45+
//
4446
// If no args are specified, args is set to []string{os.Args[0]}
4547
func NewFork(n string, fn interface{}, args ...string) (f *Function) {
4648
f = &Function{}
@@ -92,6 +94,35 @@ func (f *Function) Fork(args ...interface{}) (err error) {
9294
return
9395
}
9496

97+
// Combine NewFork and Fork with previous function configuration
98+
func (f *Function) ReFork(args ...interface{}) (err error) {
99+
previous := f.c
100+
f.c = exec.Cmd{}
101+
f.c.Path, _ = os.Executable()
102+
f.c.Args = previous.Args
103+
f.c.Stderr = f.Stderr
104+
f.c.Stdout = f.Stdout
105+
f.c.Stdin = f.Stdin
106+
f.c.SysProcAttr = f.SysProcAttr
107+
f.c.Env = os.Environ()
108+
f.c.Env = append(f.c.Env, nameVar+"="+f.Name)
109+
af, err := ioutil.TempFile("", "gofork_*")
110+
f.c.Env = append(f.c.Env, argsVar+"="+af.Name())
111+
if err != nil {
112+
return
113+
}
114+
enc := gob.NewEncoder(af)
115+
for _, iv := range args {
116+
enc.EncodeValue(reflect.ValueOf(iv))
117+
}
118+
af.Close()
119+
if err = f.c.Start(); err != nil {
120+
return
121+
}
122+
f.Process = f.c.Process
123+
return
124+
}
125+
95126
// Wait provides a wrapper around exec.Cmd.Wait()
96127
func (f *Function) Wait() (err error) {
97128
if err = f.c.Wait(); err != nil {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy