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
对于输出的重定向,对于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));