When you execute command in terminal (not background mode), if the connection disconnects unexpectedly, the running process will be terminated by SIGHUP signal. nohup
command can let process still keep running when this situation occurs.
OpenBSD
‘s nohup implementation is neat. It actually only does 4
things:
(1) If stdout
is terminal, redirect it to nohup.out
file (created in current directory or specified by HOME
environment variable):
......
if (isatty(STDOUT_FILENO))
dofile();
......
In dofile
option:
......
if (dup2(fd, STDOUT_FILENO) == -1)
err(EXIT_MISC, NULL);
......
(2) If stderr
is terminal, redirect it to stdout
. In this case, stderr
and stdout
will point to same file:
if (isatty(STDERR_FILENO) && dup2(STDOUT_FILENO, STDERR_FILENO) == -1) {
......
}
(3) Ignore SIGHUP
signal:
......
(void)signal(SIGHUP, SIG_IGN);
......
(4) Execute the intended command:
execvp(argv[1], &argv[1]);
That’s all!