8

I just run a job (assume foo.sh).

./foo.sh
[Press Ctrl-Z to stop]
bg  # enter background

And it generate output to stdout and stderr. Is there any method to redirect to stdout and stderr to other file instead of current screen?

  • Bring it to FG, redirect the output and send it back to BG. – alfasin Mar 23 '14 at 15:10
16

Apparently I misread your question the first time, so here's my updated answer:

After you sent your program to the background, you first have to find its PID

pgrep foo.sh

Then you could use gdb to attach to that process

gdb -p <PID>

In gdb you then change where this program writes to

p dup2(open("/path/to/file",577, 420), 1)
p dup2(1, 2)

then you detach from the process and quit gdb

detach
quit

A little explanation

  • 577 is equivalent to O_CREAT|O_WRONLY|O_TRUNC
  • 420 is equivalent to S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH
  • So the call to open opens the file and truncates it to 0 bytes if it exists or creates a new one with the right file permissions if it doesn't exist
  • The first call to dup2 duplicates the file descriptor returned by the call to open to file descriptor 1 (which is stdout)
  • The second call to dup2 duplicates the file descriptor 1 to 2 (which is stderr)
  • 1
    -1. Does not answer the question that was asked. Specifically, how to redirect output from a background job. – Steven Monday Mar 23 '14 at 16:01
  • 1
    Yeah, sorry, misread the question and corrected this now – s.wagner Mar 23 '14 at 17:35
  • Cool! Downvote retracted. – Steven Monday Mar 23 '14 at 23:29

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.