0

I have a program that display the log output to the stdout.

So if I open a telnet session to my target linux and then launch on this telnet session my program then I will get the log messages displayed on my telnet session.

In my program I have a little http server running. Now if I change the IP address of my target linux and then I restart the interface (the http server will restart automatically because I detect the change of ip address with netlink) And then I will get the telnet session closed and the stdout messages are redirected to the socket opened by my http server and I will get the printf of the log message locked.

I tried with select to detect this lock but without success: How to use select with stdout?

The select return success before going to the prinf (which locks)

Any suggestion to avoid this problem ?

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

1 Answers1

0

If I understand correctly, the telnet session (why aren't you using SSH??) under which the HTTP server is running becomes broken due to the change of IP address.

What will happen after that if the program continues to write data to this session (which is its stdout) is that, at first the writes will succeed as the system buffers up data, then eventually the writes will block (not "lock"). Finally, the TCP connection will time out and the writes will return an error. It may or may not take a long time for the TCP session to time out, but it eventually will.

You can make your log output code use non-blocking writes to stdout if you want to avoid blocking (e.g. if your application is event-driven and must not block). You will need to use fcntl to change stdout to non-blocking and you will probably need to avoid stdio altogether because stdio is not designed to work with non-blocking output. You must implement your own buffering and write directly to file descriptor 1.

You also mentioned that you want to log to an HTTP connection after the stdout log becomes broken. You could do that too (triggered once you get an error writing to stdout) but it will be a lot more work. You will have to manage your log buffer internally in your application until an HTTP client connects and requests it. You will also want to add a provision for discarding the log if it gets too big, in case no HTTP client connects. All of that is betyond the scope of a SO question...

Celada
  • 21,627
  • 4
  • 64
  • 78