Video source: Station B "Golang entry to project combat [2021 latest Go language tutorial, no nonsense, pure dry goods! Continuing to update...]"
While studying, organize the teacher's course content and test notes, and share them with everyone. Please move to the Zhihu website. Thank you for your support!
Attached a summary post: Go language self-study series | Summary - Zhihu (zhihu.com) https://zhuanlan.zhihu.com/p/484035621
package main
import (
"fmt"
"os"
"time"
)
func main() {
// 获得当前正在运行的进程id
fmt.Printf("os.Getegid(): %v\n", os.Getegid())
// 父id
fmt.Printf("os.Getegid(): %v\n", os.Getegid())
// 设置新进程的属性
attr := &os.ProcAttr{
// files指定新进程继承的活动文件对象
// 前三个分别为,标准输入、标准输出、标准错误输出
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
// 新进程的环境变量
Env: os.Environ(),
}
// 开始一个新进程
p, err := os.StartProcess("c:\\windows\\system32\\notepad.exe", []string{"c:\\windows\\system32\\notepad.exe", "d:\\a.txt"}, attr)
if err != nil {
fmt.Println(err)
}
fmt.Println(p)
fmt.Println("进程ID:", p.Pid)
// 通过进程ID查找进程
p2, _ := os.FindProcess(p.Pid)
fmt.Println(p2)
// 等待10秒,执行函数
time.AfterFunc(time.Second*10, func() {
// 向p进程发出退出信号
p.Signal(os.Kill)
})
// 等待进程p的退出,返回进程状态
ps, _ := p.Wait()
fmt.Println(ps.String())
}
operation result
[Running] go run "d:\SynologyDrive\软件开发\go\golang入门到项目实战\goproject\360duote.com\pro01\test.go"
os.Getegid(): -1
os.Getegid(): -1
&{9108 344 0 {
{0 0} 0 0 0 0}}
进程ID: 9108
&{9108 376 0 {
{0 0} 0 0 0 0}}
exit status 1