1

I'm trying to run a C-program in the background. I also want to save the stdout-outputs of the program.

But if I try the following, nohup only redirects stderr-outputs to the logfile.txt:

nohup ./GetTempValues 11 4 > logfile.txt 2>&1 &

Whereby 11 and 4 are the parameters I need to pass to my program and the last & is for running the program in the background (GetTempValues is my program).

3

As Guido points out above, nohup already redirects standard error for you unless you redirect it to a file. If you're using Linux, it can be instructive to run a simple command under nohup and look at the calls to dup2(2) immediately before execve(2).

I doubt you're seeing what you think you're seeing. Let's think about what happens when you say

nohup foo 2>&1
  1. The shell redirects stderr to stdout.
  2. It then invokes nohup, which inherits that situation (stderr and stdout using the same file descriptor).
  3. nohup opens nohup.out (file descriptor 3), dups it to file descriptor 1, and closes 3.
  4. nohup notices stderr is not file, and dups file descriptor 1 to 2, too. Thus file descriptors 1 and 2 both refer to nohup.out.
  5. nohup calls exec with any arguments provided on the command line (in this case, foo). The new process inherits the file descriptors that nohup set up for it.

From the command line you cannot create a case in which, as you say, nohup only redirects stderr-outputs. nohup always writes stdout and stderr to a file. stdout goes either to one you specify via redirection, or to nohup.out; stderr follows stdout unless you explicitly redirect it to another file.

The one peculiar aspect of using 2>&1 with nohup is that GNU's version produces a pointless message on stderr, nohup: ignoring input and appending output to ‘nohup.out’. (What other utility writes a message to standard error that amounts to saying, acting per documentation on instructions?) Normally that noise is written to the terminal; under redirection it winds up as the first line of the output file.

|improve this answer|||||
5

Are you sure that GetTempValues produces any standard output to begin with? Because your syntax "works for me":

$ nohup perl test.pl >logfile.txt 2>&1 &
[1] 20964
$ cat logfile.txt 
this goes to stderr
this goes to stdout
[1]+  Done                    nohup perl test.pl > logfile.txt 2>&1

where test.pl is

print STDOUT "this goes to stdout\n";
print STDERR "this goes to stderr\n";

PS: Redirecting STDERR to STDOUT with 2>&1 is not necessary with nohup in your example, because "if standard error is a terminal, it is directed to the same place as the standard output." (nohup man page).

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.