捕捉信号
// 运行此程序,控制台将打印"waiting for signal"
// 按ctrl + c 发送信号以关闭程序,将发生中断
// 随后控制台依次打印"signal .."、"exiting..."
package main
import (
"os"
"os/signal"
"syscall"
"fmt"
)
func main() {
// 缓冲通道捕捉信号
signals := make(chan os.signal, 1)
done := make(chan bool)
// notify将输入信号转发到channel
signal.notify(signals, syscall.sigint, syscall.sigterm)
go func() {
sig := <- signals
fmt.println(sig)
fmt.println("signal captured and processed...")
done <- true
}()
fmt.println("waiting for signal")
<- done
fmt.println("exiting the application...")
}
运行子进程
// 在go程序中运行其他进程
package main
import (
"os/exec"
"fmt"
)
func main() {
// command接收两个参数:命令、命令参数
// lscommand := exec.command("ls", "-a")
lscommand := exec.command("ls")
// output执行命令并返回标准输出的切片。
output, _ := lscommand.output()
//run函数阻塞进程直到lscommand执行完毕,与之类似到start函数不阻塞
lscommand.run()
// 获取进程id
fmt.println(lscommand.process.pid)
// 获取ls命令结果
fmt.println(string(output))
}
处理命令行参数
package main
import (
"os"
"fmt"
)
func main() {
// os.args的第一个元素是可执行文件路径,所以获取参数从下标1开始
realargs := os.args[1:]
if len(realargs) == 0 {
fmt.println("please pass an argument.")
return
}
if realargs[0] == "a" {
writehelloworld()
} else if realargs[0] == "b" {
writehellomars()
} else {
fmt.println("please pass a valid argument.")
}
}
func writehelloworld() {
fmt.println("hello, world!")
}
func writehellomars() {
fmt.println("hello, mars!")
}
// 执行"go run main.go a"将输出"hello, world!"
// 执行"go run main.go b"将输出"hello, mars!"