Unix alias to redirect background process output

Posted on

Problem :

I’m looking for a way to redirect the output of a background process into /dev/null or some other file.

$ python ./spam_console.py &
$ [start doing something in the foreground
$ cat test.py
$ [whole console is spammed with output of python program]

I’m looking for a way to dump the stdout, stderr of these processes to some file using a simple command line utility.

$ dump_to -p 1526 --out /dev/null

There is an excellent solution at https://superuser.com/a/732504 using the gdb, but I’m looking for a way to wrap all these behind a simple alias/c program so that it can be used easily on command line. I’m looking for help in accessing gdb in non-interactive (aka programmatic) way to execute the command in the linked article.

Solution :

I found the answer after extensive googling of hackernews. dupx exactly does what I was looking for.

Dupx is a simple utility to remap files of an already running program. Shells like Bash allow easy input/output/error redirection at the time the program is started using >, < – like syntax, e.g.:

echo 'redirect this text' > /tmp/stdout 

will redirect output of echo to /tmp/stdout.

Standard shells however do not provide the capability of remapping (redirecting) of output (or input, or error) for an already started process. Dupx tries to address this problem […]

[…]

Example usage

Note that these examples use bash syntax. First, we start a background bash job that sleeps, then prints something on standard output:

bash -c 'sleep 1m && echo rise and shine' &
  1. Redirect the remainder of standard output to /tmp/stdout

    The following invocations are equivalent:

    dupx -n 0:/tmp/test $!
    dupx -o /tmp/test $! 
    dupx $! >>/tmp/test 
    

    Note that the last example also remaps stderr and stdin of the process. But because the target process was started on the same tty as dupx is being run, they are effectively unchanged.

  2. Redirect the remainder of stdout, and stderr to different files, read the rest of stdin from /dev/null:

    The following invocations are equivalent:

    dupx -o /tmp/stdout -e /tmp/stderr -i /dev/null $! 
    dupx -n 0:/tmp/stdout 1:/dev/null 2:/tmp/stderr $! 
    dupx >/tmp/stdout 2>/tmp/stderr </dev/null $!
    

Leave a Reply

Your email address will not be published. Required fields are marked *