zoukankan      html  css  js  c++  java
  • linux后台运行之&和nohup区别,模拟后台守护进程

    先来看一下&的使用

    root@BP:~# cat test.sh
    #!/bin/bash
    while true
    do
            echo "linux">/dev/null
    done
    root@BP:~# ./test.sh &     #&后台运行
    [1] 4599
    root@BP:~# ps         #test.sh运行中
      PID TTY          TIME CMD
     4555 pts/1    00:00:00 bash
     4599 pts/1    00:00:00 test.sh
     4600 pts/1    00:00:00 ps
    root@BP:~# exit    
    root@BP:~# ps              #终端退出后程序也跟着退出了
      PID TTY          TIME CMD
     4611 pts/2    00:00:00 bash
     4617 pts/2    00:00:00 ps
    root@BP:~# 
    
    

    再来看一下nohup,使用该命令会在当前目录下产生nohup.out文件,该文件类似日志文件,程序的输出直接记录到该文件,不过我这里直接/dev/null了,所以那个文件会是空的

    根据下面的步骤执行,就不会出现nohup随着终端关闭而停止程序的情况了,特别是退出方式那里特别需要注意(这个是别人说的,经过我实验nohup ./test.sh &回车后直接点击关闭窗口也没有什么影响)
    就我个人来说,我就是老是以为可以直接用ps查看到这个进程,导致我在这里卡了很久而已

    root@BP:~# cat test.sh
    #!/bin/bash
    while true
    do
            echo "linux">/dev/null
    done
    root@BP:~# ps -aux|grep test.sh
    root      5093  0.0  0.0  12720   932 pts/2    S+   09:10   0:00 grep test.sh
    root@BP:~# nohup ./test.sh &
    [1] 5094
    root@BP:~# nohup: ignoring input and appending output to 'nohup.out'  #需要回车一下,继续执行下面命令
    
    root@BP:~# ps           #我一直在这里查看test.sh有没有运行其实是错误的
      PID TTY          TIME CMD
     4716 pts/2    00:00:00 bash
     5094 pts/2    00:00:21 test.sh
     5096 pts/2    00:00:00 ps
    root@BP:~# ps -aux|grep test.sh    #应该这样子看才对
    root      5094 98.8  0.0  11156  2716 pts/2    R    09:10   1:22 /bin/bash ./test.sh
    root      5102  0.0  0.0  12720   940 pts/2    S+   09:12   0:00 grep test.sh
    root@BP:~# exit               #需要以这种方式退出终端
    #退出终端后,再重新开一个终端执行下面命令
    root@BP:~# ps
      PID TTY          TIME CMD
     5132 pts/1    00:00:00 bash
     5138 pts/1    00:00:00 ps
    root@BP:~# ps -aux|grep test.sh       #可以看到程序并没有停止,注意5094是pid
    root      5094 99.0  0.0  11156  2716 ?        R    09:10   5:50 /bin/bash ./test.sh
    root      5142  0.0  0.0  12720   944 pts/1    S+   09:16   0:00 grep test.sh
    root@BP:~# 
    
    扩展一下:怎么杀死这个后台进程
    root@BP:~# kill -9 5094
    root@BP:~# ps -aux|grep test.sh
    root      5163  0.0  0.0  11116   936 pts/1    D+   09:20   0:00 grep test.sh
    
  • 相关阅读:
    TP5 自带封装分页查询
    TP5 接口 前面拼接 当前域名
    button按钮点击后过段时间不能点击-验证码(刷新后失效)
    关于PHP -session 的 A session had already been started – ignoring session_start() 错误
    301 Moved Permanently
    PHP实现远程下载图片与 图片接口定义
    在TP框架的前端中 想引用 PHP的函数
    流程控制语句2
    流程控制语句
    数据库查询数据2
  • 原文地址:https://www.cnblogs.com/biaopei/p/7730540.html
Copyright © 2011-2022 走看看