如何分叉一个进程

huangapple go评论70阅读模式
英文:

How to fork a process

问题

我需要帮助理解如何在Go中使进程脱离终端。

package main

import (
   "fmt"
   "os"
)

func start() {
   var procAttr os.ProcAttr 
   procAttr.Files = []*os.File{nil, nil, nil}
   _, err := os.StartProcess("/Path/prog", nil, &procAttr)
   if err != nil {
       fmt.Printf("%v", err)
   }
}


func main () {
   start()
}

如果在命令行上启动此代码,程序会返回控制权,但仍与cmd连接。关闭cmd会关闭程序。

如何使其与cmd解耦?添加以下代码:

procAttr.Sys.HideWindow = true

会导致以下错误:"panic" to wrong memory pointer

英文:

I need help understanding how to demonize a process in Go.

package main

import (
   "fmt"
   "os"
)

func start() {
   var procAttr os.ProcAttr 
   procAttr.Files = []*os.File{nil, nil, nil}
   _, err := os.StartProcess("/Path/prog", nil, &procAttr)
   if err != nil {
       fmt.Printf("%v", err)
   }
}


func main () {
   start()
} 

If you start this code on the command line the program returns control, but is still connected with cmd. Closing the cmd closes the program.

How can I decouple it from the cmd? Adding:

procAttr.Sys.HideWindow = true

Results in this error: "panic" to wrong memory pointer

答案1

得分: 10

我在'golang-nuts'中询问,并发现Go有一个链接选项:

go tool 8l -o output.exe -Hwindowsgui input.8

英文:

I asked in 'golang-nuts', and found out that Go has a link option:

go tool 8l -o output.exe -Hwindowsgui input.8

答案2

得分: 2

这里有一个用Go语言编写的虚拟守护进程,使用起来很简单:https://github.com/icattlecoder/godaemon

一个示例:

package main

import (
    _ "github.com/icattlecoder/godaemon"
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/index", func(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte("hello, golang!\n"))
    })
    log.Fatalln(http.ListenAndServe(":7070", mux))
}
英文:

Here is a fake daemon in go; it's simple to use: https://github.com/icattlecoder/godaemon

An example:

package main

import (
    _ "github.com/icattlecoder/godaemon"
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/index", func(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte("hello, golang!\n"))
    })
    log.Fatalln(http.ListenAndServe(":7070", mux))
}

huangapple
  • 本文由 发表于 2012年4月5日 19:11:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/10027477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定