zoukankan      html  css  js  c++  java
  • [Linux] nohup/setsid/& 让进程在后台可靠运行

    当用户注销(logout)或者网络断开时,终端会收到 HUP(hangup)信号从而关闭其所有子进程。因此,我们的解决办法就有两种途径:要么让进程忽略 HUP 信号,要么让进程运行在新的会话里从而成为不属于此终端的子进程

    (hangup 名称的来由:在 Unix 的早期版本中,每个终端都会通过 modem 和系统通讯。当用户 logout 时,modem 就会挂断(hang up)电话。 同理,当 modem 断开连接时,就会给终端发送 hangup 信号来通知其关闭所有子进程)

    1.nohup:让提交的命令忽略 hangup 信号

    nohup 的帮助信息:

    $ nohup --help
    
    Usage: nohup COMMAND [ARG]... or: nohup OPTION
    Run COMMAND, ignoring hangup signals.
    --help display this help and exit --version output version information and exit If standard input is a terminal, redirect it from an unreadable file. If standard output is a terminal, append output to 'nohup.out' if possible, '$HOME/nohup.out' otherwise. If standard error is a terminal, redirect it to standard output. To save output to FILE, use 'nohup COMMAND > FILE'.

    使用:在要处理的命令前加上 nohup 即可,标准输出和标准错误缺省会被重定向到 nohup.out 文件中。一般我们可在结尾加上"&"来将命令同时放入后台运行,也可用"> filename"来更改缺省的重定向文件路径。

    nohup ping www.baidu.com &
    nohup python train_model.py > console.log &

    2.setsid:在新session执行命令(使进程不属于接受 HUP 信号的终端的子进程,那么就不会受到 HUP 信号的影响)

    setsid的帮助信息:

    $ setsid --help
    
    Usage:
     setsid [options] <program> [arguments ...]
    
    Run a program in a new session.
    
    Options:
     -c, --ctty     set the controlling terminal to the current one
     -w, --wait     wait program to exit, and use the same return
     -h, --help     display this help and exit
     -V, --version  output version information and exit

    使用:

    setsid ping www.ibm.com &

    另外,查看进程并停止:

    $ ps -ef | grep ping
    abby      3899  1632  0 14:39 ?        00:00:00 ping www.baidu.com
    abby      4038  3907  0 14:43 pts/20   00:00:00 grep --color=auto ping
    
    $ kill -9 3899

    参考:

    Linux 技巧:让进程在后台可靠运行的几种方法

  • 相关阅读:
    SpringBoot_web开发-【实验】-员工列表-公共页抽取
    下载 Linux 内核的脚本
    uboot 修改代码 增加 环境变量
    Linux FHS
    Redis源码分析(二十五)--- zmalloc内存分配实现
    Redis源码分析(二十四)--- tool工具类(2)
    Redis源码分析(二十四)--- tool工具类(2)
    数据结构(二)——排序
    数据结构(一)——树
    python(三)——while语句
  • 原文地址:https://www.cnblogs.com/bymo/p/7373349.html
Copyright © 2011-2022 走看看