• nohup原理


    nohup

    nohup 执行会忽略信号 SIGHUP,并将 stdout/stderr 重定向到文件 nohup.out。以便shell在关闭或注销后命令可以在后台继续运行 。nohup做的工作就是让 nohup 后的命令不在是当前 shell 的子命令。而是PPID=1的进程(进程的PPID=1)。这种情况下不能被带回到前台。

    signal (SIGHUP, SIG_IGN); // 忽略信号SIGHUP
    
    char **cmd = argv + optind;
    execvp (*cmd, cmd); // 在执行这个命令,而不是当前shell
    
    • 1
    • 2
    • 3
    • 4

    对于输出的重定向,对于STDOUT/STDERR会忽略,然后写入到 nohup.out

      ignoring_input = isatty (STDIN_FILENO);
      redirecting_stdout = isatty (STDOUT_FILENO);
      stdout_is_closed = (!redirecting_stdout && errno == EBADF);
      redirecting_stderr = isatty (STDERR_FILENO);
    
      /* If standard input is a tty, replace it with /dev/null if possible.
         Note that it is deliberately opened for *writing*,
         to ensure any read evokes an error.  */
      if (ignoring_input)
        {
          if (fd_reopen (STDIN_FILENO, "/dev/null", O_WRONLY, 0) < 0)
            error (exit_internal_failure, errno,
                   _("failed to render standard input unusable"));
          if (!redirecting_stdout && !redirecting_stderr)
            error (0, 0, _("ignoring input"));
        }
    
      /* If standard output is a tty, redirect it (appending) to a file.
         First try nohup.out, then $HOME/nohup.out.  If standard error is
         a tty and standard output is closed, open nohup.out or
         $HOME/nohup.out without redirecting anything.  */
      if (redirecting_stdout || (redirecting_stderr && stdout_is_closed))
        {
          char *in_home = NULL;
          char const *file = "nohup.out";
          int flags = O_CREAT | O_WRONLY | O_APPEND;
          mode_t mode = S_IRUSR | S_IWUSR;
          mode_t umask_value = umask (~mode);
          out_fd = (redirecting_stdout
                    ? fd_reopen (STDOUT_FILENO, file, flags, mode)
                    : open (file, flags, mode));
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    Referece what is the function of the nohup command

  • 相关阅读:
    【ElasticSearch】6亿文档存储的ES集群调优实战
    【C语言】指针传参引发的相关问题
    BFS和DFS
    Python Day13 面向对象基础【初级】
    OpenVINO 2023.0 实战七:OpenVINO部署PaddleOCR v4模型
    探究精酿啤酒的秘密:原料中的天然酵母与纯净水质
    32 数据分析(下)pandas介绍
    7.Gin 路由详解 - 路由分组 - 路由文件抽离
    浅拷贝和深拷贝
    Redis介绍、安装、性能优化
  • 原文地址:https://blog.csdn.net/sinat_24092079/article/details/126053605