Hi bluhm, Thanks very much for your time and detailed explanation!
I update the patch, and you can review it when you are free, thanks! Index: nohup.c =================================================================== RCS file: /cvs/src/usr.bin/nohup/nohup.c,v retrieving revision 1.17 diff -u -p -r1.17 nohup.c --- nohup.c 26 Apr 2018 12:42:51 -0000 1.17 +++ nohup.c 14 Sep 2018 07:04:10 -0000 @@ -78,13 +78,14 @@ main(int argc, char *argv[]) if (argc < 2) usage(); - if (isatty(STDOUT_FILENO)) + if (isatty(STDOUT_FILENO) || errno == EBADF) dofile(); if (pledge("stdio exec", NULL) == -1) err(1, "pledge"); - if (isatty(STDERR_FILENO) && dup2(STDOUT_FILENO, STDERR_FILENO) == -1) { + if ((isatty(STDERR_FILENO) || errno == EBADF) && + dup2(STDOUT_FILENO, STDERR_FILENO) == -1) { /* may have just closed stderr */ (void)fprintf(stdin, "nohup: %s\n", strerror(errno)); exit(EXIT_MISC); @@ -125,6 +126,8 @@ dupit: (void)lseek(fd, (off_t)0, SEEK_END); if (dup2(fd, STDOUT_FILENO) == -1) err(EXIT_MISC, NULL); + if (fd > STDERR_FILENO) + (void)close(fd); (void)fprintf(stderr, "sending output to %s\n", p); } On 9/12/2018 8:17 PM, Alexander Bluhm wrote: > On Sun, Sep 09, 2018 at 11:13:40AM +0800, Nan Xiao wrote: >> Honestly, I am still a little confused: > > Let's explain more context. Recently I found some deamons that > accidently closed stdin, so I am sensible for this kind of error. > > nohup(1) tries to use nohup.out for stdout or stderr in some cases. > If the file descriptors are closed in advance, this does not work. > To fix these additional cases, I think we should also redirect to > nohup.out if stdout or stderr is closed. > >> "nohup true 2>&-" means close stderr of nohup, right? > > Yes. > >>> errno = 0; >>> if (isatty(STDOUT_FILENO) || errno == EBADF) >> >> Since we close stderr, why do we need additional check of stdout here? > > We should check both stdout and stderr. This is just an example > how the check could work. Logic should be to redirect stdout or > stderr to nohup.out, if it is a tty or if it has been closed. > > bluhm > -- Best Regards Nan Xiao