github.com/AlpineAIO/wails/v2@v2.0.0-beta.32.0.20240505041856-1047a8fa5fef/internal/process/process.go (about)

     1  package process
     2  
     3  import (
     4  	"os"
     5  	"os/exec"
     6  )
     7  
     8  // Process defines a process that can be executed
     9  type Process struct {
    10  	cmd         *exec.Cmd
    11  	exitChannel chan bool
    12  	Running     bool
    13  }
    14  
    15  // NewProcess creates a new process struct
    16  func NewProcess(cmd string, args ...string) *Process {
    17  	result := &Process{
    18  		cmd:         exec.Command(cmd, args...),
    19  		exitChannel: make(chan bool, 1),
    20  	}
    21  	result.cmd.Stdout = os.Stdout
    22  	result.cmd.Stderr = os.Stderr
    23  	return result
    24  }
    25  
    26  // Start the process
    27  func (p *Process) Start(exitCodeChannel chan int) error {
    28  	err := p.cmd.Start()
    29  	if err != nil {
    30  		return err
    31  	}
    32  
    33  	p.Running = true
    34  
    35  	go func(cmd *exec.Cmd, running *bool, exitChannel chan bool, exitCodeChannel chan int) {
    36  		err := cmd.Wait()
    37  		if err == nil {
    38  			exitCodeChannel <- 0
    39  		}
    40  		*running = false
    41  		exitChannel <- true
    42  	}(p.cmd, &p.Running, p.exitChannel, exitCodeChannel)
    43  
    44  	return nil
    45  }
    46  
    47  // Kill the process
    48  func (p *Process) Kill() error {
    49  	if !p.Running {
    50  		return nil
    51  	}
    52  	err := p.cmd.Process.Kill()
    53  	if err != nil {
    54  		return err
    55  	}
    56  	err = p.cmd.Process.Release()
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	// Wait for command to exit properly
    62  	<-p.exitChannel
    63  
    64  	return err
    65  }
    66  
    67  // PID returns the process PID
    68  func (p *Process) PID() int {
    69  	return p.cmd.Process.Pid
    70  }
    71  
    72  func (p *Process) SetDir(dir string) {
    73  	p.cmd.Dir = dir
    74  }