1

I want to SSH into a machine, start a process, write the stdErr and stdOut of the process into two seperate files while reading the stdOut/stdErr in the console. As soon as some specific lines were written in the stdOut/stdErr (of the console), I want to disconnect the SSH session, while keeping the process running in the background.

At the moment I'm using nohup to start the process in the background, log stdout and stderr to a file and return the pid of the started process. What is missing is the part where I can still get the stdOut/stdErr from the console, till I decide that I want to disconnect the SSH session, while letting the process run in the background.

Here is a simple example with a ping script

test.sh:

#!bin/bash
nohup bash ~/ping.sh > foo.out 2> foo.err & echo $!

ping.sh:

#!bin/bash
/bin/ping -c 8 superuser.com
1

tail does what you want. You need two features of tail in order to make it work for your case. The first one is that tail allows you to 'follow' (keep on watching) file contents as the files grow: (from the manpage)

-f, --follow[={name|descriptor}]
    output appended data as the file grows; -f, --follow, and
        --follow=descriptor are equivalent

The second feature is that tail accepts multiple files, even when using -f.

I tested it with the following C program:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    int i;
    setlinebuf(stdout);
    setlinebuf(stderr);
    for (i = 0; i < 10; i++) {
        fprintf(stdout, "message on stdout ...\n");
        sleep(1);
        fprintf(stderr, "message on stderr ...\n");
        sleep(1);
    }
    return 0;
}

Output:

$ nohup ./prog > foo.out 2> foo.err & echo $!
9778
$ tail -f foo.out foo.err
==> foo.out <==
message on stdout ...

==> foo.err <==
message on stderr ...

==> foo.out <==
message on stdout ...

==> foo.err <==
message on stderr ...

==> foo.out <==
message on stdout ...

and so on. Note that the messages alternate nicely one by one in this case, but that may not always be true. You probably want to enable line buffering (as I did in the sample program) unless you don't mind the output arriving in 'chunks'.

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.