How to signal parent process with child's status

On POSIX systems, my Go program calls syscall.ForkExec() to start a child process, feeding it some yummy bytes through stdin. After the child process has started successfully, I want my parent process to exit - but only if the child didn’t have any errors when it started. Both processes are long-running, so waiting for an exit code is out of the question. Also it may do this ‘restart’ every second or more, so waiting a few seconds to see if the PID is still there isn’t ideal, either.

Here’s my fork code:

// Fork the process with the current environment and file descriptors
execSpec := &syscall.ProcAttr{
	Env:   os.Environ(),
	Files: fds, // fds was created earlier with an os.Pipe, etc...
}
pid, err := syscall.ForkExec(os.Args[0], os.Args, execSpec)
if err != nil {
	return err
}

// Feed it some data to initialize itself with
_, err = io.Copy(wpipe, data)
if err != nil {
	return err
}
wpipe.Close()

// TODO: Make sure child started successfully with the data we piped it

// Once child process is working, stop this process
os.Exit(0)

What is the recommended way to do this? Should the child signal the parent? If so, using which signals to indicate success/failure?

I would suggest passing a pipe to the child process, and having the child process write a success indicator to the pipe. If the child process simply exits, the write end of the pipe will close, and you will know that the child did not succeed.

2 Likes

That’s a good idea. How do I pass the pipe? Do I just use os.Pipe again and put it in the Files property of the syscall.ProcAttr? (I will try it soon anyway.)

Yes.

Be sure to close the parent’s copy of the write end of the pipe before reading from the read end.

That works - thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.