Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: stdout and stderr to socket

I want to redirect stdout and stderr to a socket that I can then use to remotely monitor the status of my application over Ethernet. Currently I accomplish this by using ssh and watching the output in the shell console. I'd prefer to remove the middle man if possible and just send the entire stdout and stderr output to a udp or tcp/ip port and have my monitoring computer connect to it.

I cannot use UART or any other wired connection. It has to be Ethernet. Also, if possible, I'd like to accomplish this via a bash script, to prevent having to rebuild my application.

Thanks for the help.

like image 307
It'sPete Avatar asked Mar 19 '14 01:03

It'sPete


2 Answers

The way you describe it, it sounds like your going to need either your existing application to open a passive socket and wait for connections, or your going to have to wrap your application in something that sets up a listening socket. This post suggests that is not possible in just Bash, however it does show ways to do it from the command line with netcat or perl. For example you could do something like this with netcat: nc -l -p <port> -c "tail -F /var/log/blah"

like image 178
spinkus Avatar answered Oct 23 '22 12:10

spinkus


On the monitored application side, there is a way to redirect both outputs to an outbound connection, using netcat:

$ ./application 2>&1 | nc <remote-host> <remote-port>

This way, you're redirecting stderr to stdout and then pipe it all together to netcat, which will take care of setting up the socket, establish connection with the remote host and all that stuff.

However, bear in mind that you can suffer from printf()'s buffering, if that's the function you're using to write to stdout. In my local tests, I've seen that the data sent to stderr by the application is seen immediately on the other listening end, but on the other hand the data sent to stdout is only sent when the application exits or there's enough data in the buffer to flush it all at once. So, if you care about the order and the availability of the info on the monitoring side, I'd suggest you to place calls to fflush(stdout); whenever you print something interesting to stdout, or replace the calls to printf(), fprintf() and the like to write(), which does not buffer. The downside is that you have to touch the code of the application, of course, but I don't know any way to externally force flushing of an application's output buffers (i.e. from bash).

like image 6
asamarin Avatar answered Oct 23 '22 12:10

asamarin