0

I have below solution to record a command and its output executed on a remote machine:

rexec:// -t -t /usr/bin/ssh -q -x -o StrictHostKeyChecking=no -2 \
         -l ${SSHUserName} -p 22 ${mainHost} \
 | tee >(/opt/oss/clilogging/bin/clilogging.sh para1 para2)

clilogging.sh will record each command and its output into a log file.
However, sometimes the last exited command and its output message "logout" is not written into the log file.

clilogging.sh is as follows:

#!/bin/bash

{
    while read R || [ -n "$R" ];do
        #e.g. 2013-08-19T09:58:08+0300
        timestamp=`date +%FT%T%z`;
        echo $timestamp $R;
    done
} > /tmp/xxx.log

Could anybody help me? Thanks a lot!

Alfe
  • 56,346
  • 20
  • 107
  • 159
Jeff7566
  • 432
  • 1
  • 5
  • 20
  • 1
    I don't see clear here, but I have the strong feeling that the output gets buffered and then that buffer doesn't get a chance to get flushed in the end. Probably the process buffering something is just killed. – Alfe Nov 05 '13 at 09:26
  • @Alfe what if I use ctrl + D to logout from shell ?? – Ashish Nov 05 '13 at 09:55
  • What is the reason that you redirect (>) the output of tee to clilogging.sh instead of piping (|) ? – thom Nov 06 '13 at 14:18
  • @Alfe I think you are right. File-redirection to a shell gets buffered in the tmp filesystem and is flushed in in it's own time. Since this is a sub process, it will be killed if the parent exits sooner. To be sure about this the code above should be extended with a "wait" – thom Nov 06 '13 at 17:59
  • `@thom` tee >(clilogging.sh) no only sent output to clilogging.sh but also print to stdout. – Jeff7566 Nov 07 '13 at 02:44
  • `@Alfe` I agree with you. But this issue is not 100% reproduced. It is hard to figure out the buffer missing on ssh to tee or tee to clilogging.sh. – Jeff7566 Nov 07 '13 at 02:59

1 Answers1

1

Thanks thom's comment and thank you all.
I have found the solution of this issue.

Need add following code at the begining of clilogging.sh

trap "" HUP

The meaning of code is to handle SIGHUP signal, here I ignore this signal, then clilogging.sh
will not quit immediately and have the chance to handle all buffer.

man 7 signal

   Signal     Value     Action   Comment
   -------------------------------------------------------------------------
   SIGHUP        1       Term    Hangup detected on controlling terminal
                                 or death of controlling process
Jeff7566
  • 432
  • 1
  • 5
  • 20