Process.go
package core
import (
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
)
// Execute ํจ์๋ ์ฃผ์ด์ง ๋ช
๋ น์ด๋ฅผ ์คํํฉ๋๋ค.
func Execute(command string) error {
if runtime.GOOS == "windows" {
cmd := exec.Command("cmd", "/C", command)
return cmd.Start()
} else {
cmd := exec.Command("sh", "-c", command+" > /dev/null 2>&1 &")
return cmd.Start()
}
}
// Spawn ํจ์๋ ์ฃผ์ด์ง ๋ฐ์ด๋๋ฆฌ์ ์๋น์ค๋ฅผ ๋ฐฑ๊ทธ๋ผ์ด๋์์ ์คํํฉ๋๋ค.
func Spawn(bin string, service string, inputs []string) error {
log("Spawn process.. " + service)
if runtime.GOOS == "windows" {
args := append([]string{"php", bin, service}, inputs...)
cmd := exec.Command("cmd", "/C", strings.Join(args, " "))
return cmd.Start()
} else {
php, err := exec.LookPath("php")
if err != nil {
return err
}
args := append([]string{php, bin, "run", service}, inputs...)
cmd := exec.Command("sh", "-c", strings.Join(args, " ")+" > /dev/null 2>&1 &")
return cmd.Start()
}
}
// Fork ํจ์๋ ์ฃผ์ด์ง ๋ฐ์ด๋๋ฆฌ์ ์๋น์ค๋ฅผ ์๋ก์ด ์ธ์
์์ ์คํํฉ๋๋ค.
func Fork(bin string, service string, inputs []string) error {
log("Fork process.. " + service)
if runtime.GOOS == "windows" {
return fmt.Errorf("Fork is not supported on Windows")
}
php, err := exec.LookPath("php")
if err != nil {
return err
}
args := append([]string{php, bin, service}, inputs...)
cmd := exec.Command(php, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
return cmd.Start()
}
// IsRunning ํจ์๋ ์ฃผ์ด์ง PID์ ํ๋ก์ธ์ค๊ฐ ์คํ ์ค์ธ์ง ํ์ธํฉ๋๋ค.
func IsRunning(pid int) bool {
if runtime.GOOS == "windows" {
cmd := exec.Command("tasklist", "/NH", "/FO", "CSV", "/FI", fmt.Sprintf("PID eq %d", pid))
output, err := cmd.Output()
if err != nil {
fmt.Println("Error checking process:", err)
return false
}
return strings.Contains(string(output), fmt.Sprintf("%d", pid))
} else {
process, err := os.FindProcess(pid)
if err != nil {
return false
}
err = process.Signal(syscall.Signal(0))
return err == nil
}
}
// Destroy ํจ์๋ ์ฃผ์ด์ง PID์ ํ๋ก์ธ์ค๋ฅผ ๊ฐ์ ์ข
๋ฃํฉ๋๋ค.
func Destroy(pid int) error {
log(fmt.Sprintf("Kill process.. %d ", pid))
if runtime.GOOS == "windows" {
cmd := exec.Command("taskkill", "/PID", fmt.Sprintf("%d", pid), "/F")
return cmd.Run()
} else {
process, err := os.FindProcess(pid)
if err != nil {
return err
}
return process.Kill()
}
}
// log ํจ์๋ ์ฃผ์ด์ง ๋ฉ์์ง๋ฅผ ์ถ๋ ฅํฉ๋๋ค. (์์๋ก fmt.Println์ผ๋ก ๋์ฒด)
func log(message string) {
fmt.Println(message)
// ์ฌ๊ธฐ์ ํ์ํ ๋ก๊ทธ ๊ธฐ๋ก ๋ก์ง์ ์ถ๊ฐํ์ธ์
}
์ฃผ์ ํจ์
์์ฝ
Last updated