终端后台运行命令的方法

作者: BlackChen | 来源:发表于2017-03-24 13:04 被阅读146次

    test 测试程序

    #include <stdio.h>
    int main()
    {
            while(1)
            {
                    sleep(1);
                    printf("hello \n");
            }
            return 0;
    }
    
    1. nohup
    cc@MyLinux:~/test$ nohup ./test>file&
    [1] 1647
    cc@MyLinux:~/test$ nohup: ignoring input and redirecting stderr to stdout
    

    关闭终端,打开另外一个终端,test 依然在运行

    cc@MyLinux:~/test$ ps 1647
       PID TTY      STAT   TIME COMMAND
      1647 ?        R      0:31 ./test
    

    此程序还在运行,并没有受到SIGHUP信号。

    1. 使用括号 和 &
      在一个终端中执行以下命令,test进入后台。
    cc@MyLinux:~/test$ (./test >file &)
    cc@MyLinux:~/test$ ps aux |grep test
    cc         1695 71.0  0.0   4360   688 pts/1    R    09:02   0:09 ./test
    cc         1697  5.0  0.1  14228  1028 pts/1    S+   09:02   0:00 grep --color=auto test
    

    关闭终端后,在另外一个终端中查看,进程依然在运行

    cc@MyLinux:~/test$ ps 1659
       PID TTY      STAT   TIME COMMAND
    cc@MyLinux:~/test$ ps aux | grep test
    cc         1695 68.9  0.0   4360   688 ?        R    09:02   0:30 ./test
    cc         1700  0.0  0.1  14228  1028 pts/2    S+   09:03   0:00 grep --color=auto test
    cc@MyLinux:~/test$ kill -9 1695
    

    原理:

    cc@MyLinux:~/test$ (./test > file&)
    cc@MyLinux:~/test$ ps -ef | grep test
    cc         1738      1 74 09:06 pts/1    00:00:07 ./test
    cc         1740   1724  0 09:06 pts/1    00:00:00 grep --color=auto test
    

    新创建的进程的父进程是1,是init进程,不是当前终端的进程ID,因此并不属于当前终端的子进程,从而也就不会受到当前终端的 HUP 信号的影响了。

    1. setsid
    [posp@hadoop01 chenchen_test]$ setsid ./print > file &
    [1] 30782
    
    [posp@hadoop01 ~]$ ps -ef | grep print
    posp     30751     1  0 12:43 ?        00:00:00 ./print
    posp     30759 30727  0 12:43 pts/3    00:00:00 grep print
    

    setsid 本质上和()& shell 的这个方法是相同的,都是让此进程不再终端发送sighup信号的进程中.

    1. 使用<ctrl + z> fg,bg, jobs
      Ctrl + Z 用途就是将当前进程挂起(Suspend),我们使用ctrl +z 将当前进程挂起后,可以执行一些其他命令,然后再使用fg 将此进程唤醒,使用jobs来查看被挂起的进程.
      例如: 正在使用vim编辑代码,然后需要查看一下当前目录,可以使用Ctrl+z挂起进程,查看后,再使用fg唤醒,继续之前的操作.
    [mpos@hadoop02 RmFunc]$ jobs
    [1]+  Stopped                 vim C00002.c
    [2]-  Stopped                 vim C00004.c
    
    [mpos@hadoop02 RmFunc]fg
    [mpos@hadoop02 RmFunc]bg
    

    相关文章

      网友评论

        本文标题:终端后台运行命令的方法

        本文链接:https://www.haomeiwen.com/subject/mbganttx.html