Another method is exec.Command
In addition to completing tasks, it is also very easy to hide the window. That is, you will not see the console flash on windowless.
cmd := exec.Command("powershell", "del", os.Args[0])
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
if err := cmd.Start(); err != nil {
panic(err)
}
Example
Since we delete the executable files, you should ensure that all programs have been appropriately processed before deleting. I recommend that you use chan to communicate.
kill.go
package main
import ("io";"log";"os";"os/exec";"syscall")
var (
chanQuit chan bool
logger *log.Logger
)
func init() {
chanQuit = make(chan bool)
}
func ListenToDeleteApp(ch chan bool) {
select {
case killNow, _ := <-ch:
if killNow {
cmd := exec.Command("powershell", "del", os.Args[0])
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
if err := cmd.Start(); err != nil {
panic(err)
}
logger.Println("delete own executable")
close(chanQuit)
}
}
}
func main() {
// Because we build a windowless application, so use a file to simulate the output.
f, _ := os.OpenFile("temp_log.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm) // for clear, we don't do check the error
logger = log.New(io.MultiWriter(f), "", log.Ltime)
defer func() {
logger.Println("close logger")
f.Close()
}()
chanKill := make(chan bool)
go ListenToDeleteApp(chanKill)
go func() { // main process
logger.Println("do something...")
needKill := true // do some logic you want to delete
if needKill {
chanKill <- true
return
}
logger.Println("quit app without delete executable")
close(chanQuit)
}()
select {
case <-chanQuit:
logger.Println("End")
return
}
}
build cmd:
go build -ldflags "-H=windowsgui -s -w" kill.go
run:
kill.exe
output:
HH:MM:SS do something...
HH:MM:SS delete own executable
HH:MM:SS End
HH:MM:SS close logger