doudui1850 2012-09-18 23:49
浏览 425
已采纳

如何使Golang Web服务器在后台运行?

I have recently completed the Wiki web development tutorial (http://golang.org/doc/articles/wiki/). I had tons of fun and I would like to experiment more with the net/http package.

However, I noticed that when I run the wiki from a console, the wiki takes over the console. If I close the console terminal or stop the process with <kbd>CTRL+Z</kbd> then the server stops.

How can I get the server to run in the background? I think the term for that is running in a daemon.

I'm running this on Ubuntu 12.04. Thanks for any help.

  • 写回答

3条回答 默认 最新

  • dongni8124 2012-09-19 00:03
    关注

    Simple / Usable things first

    If you want a start script without much effort, you could use the upstart service. See the corresponding manual page and /etc/init/*.conf for examples. After creating such a process you can start your server by calling

    service myserver start
    

    If you want more features, like specific limitations or permission management, you could try xinetd.

    Using the shell

    You could start your process like this:

    nohup ./myexecutable &
    

    The & tells the shell to start the command in the background, keeping it in the job list. On some shells, the job is killed if the parent shell exits using the HANGUP signal. To prevent this, you can launch your command using the nohup command, which discards the HANGUP signal.

    However, this does not work, if the called process reconnects the HANGUP signal.

    To be really sure, you need to remove the process from the shell's joblist. For two well known shells this can be achieved as follows:

    bash:

    ./myexecutable &
    disown <pid>
    

    zsh:

    ./myexecutable &!
    

    Killing your background job

    Normally, the shell prints the PID of the process, which then can be killed using the kill command, to stop the server. If your shell does not print the PID, you can get it using

    echo $!
    

    directly after execution. This prints the PID of the forked process.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含