The CPU load from the main program rises when the subroutine closes

I have a web service that, upon request, runs a command running in the background:

cmd := exec.Command(instPath, settings.ExecWorkingDir+settings.ExecFileEnvPath, settings.ExecWorkingDir+settings.ExecFileLogPath, ":"+freeport, id)
	if err := cmd.Start(); err != nil {
		return nil, err
	}

	e.Pid = cmd.Process.Pid

	go func() {
		_ = cmd.Wait()
	}()

	go e.loop()
	return e, nil
func (e *Exec) loop() {
	defer e.stop()
	for e.Work {
		p, err := os.FindProcess(e.Pid)
		if err != nil {
			e.Err = true
			e.Block = true
			return
		} else {
			err := p.Signal(syscall.Signal(0))
			if err != nil {
				e.Err = true
				e.Block = true
				return
			}
		}
	}
}

The loop method checks whether the subroutine is working, and if it is completed, it exits the loop and the stop method is triggered. It works correctly. But when the subprogram is killed, the CPU load from the web service (main program) rises by 300%.
I use OS Linux, Elementary OS

Hi. Your code isn’t really complete what structure is e? loop is a really tight loop. Maybe you could make it sleep some every iteration

time.Sleep(100 * time.Millisecond)

And also why do you have to find the process with pid and see if it has ended instead of using cmd.Wait() ?

I already tried to set a delay for each iteration, it did’t help.
Structure E does not have a special meaning; we will assume that it serves to preserve the value of the PID. I can’t use Wait () because I need to return some data, and the command that I run can work forever, it’s a kind of daemon,and the Wait () method will wait for the completion of the subroutine.

And again, if I do not use the wait () method, when I kill a subroutine, I will get “process defunct”. That means process become zombie, he’s killed, but main process still waiting some action from subroutine

Closed! Bug was find in socket library

1 Like

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