Tookmund / Swapspace

A fork of Jeroen T. Vermeulen's excellent dynamic swap space manager
GNU General Public License v2.0
139 stars 13 forks source link

swapspace buffers stdout in systemd, which makes SIGUSR1 not show in journalctl #44

Closed adamsmd closed 1 week ago

adamsmd commented 1 month ago

Problem

Running swapspace under systemd seems to have stdout (non-line) buffering on. This means that calls to kill -SIGUSR1 do not show in journalctl -u swapspace.service immediately (though repeated calls will eventually fill the buffer causing the buffer to flush to stdout).

Suspected Cause

I am not in a position to test this, but I suspect this is due to the C standard library's default buffering behavior, which is to line buffer on TTYs but (non-line) buffer on anything else, and that under systemd the stdout is not a TTY.

Suggested Change

As far as I can tell, swapspace does not currently provide a direct way to resolve this, so I would suggest a change like one of the two following (though I don't know enough about your design to know which is best).

Option 1: Have swapspace call setlinebuffer or setvbuf explicitly.

Option 2: Have the logging methods in swapspace explicitly call flush() after printing.

I think that swapspace outputs small enough amounts of output that one could have these always on, but you could also have these controlled by a configuration/command-line flag.

Option 1 has the advantage of covering all outputs without having to worry about missing any, but Option 2 gives you the option of controlling which outputs flush the buffer.

Workaround

A wrapper such as expect's unbuffer is working for me in the meantime. Thus, my swapspace.service file contains:

ExecStart=/usr/bin/unbuffer /usr/bin/swapspace ...

My understanding is that unbuffer simulates a TTY on the stdout of swapspace, which makes the C library use line buffering for stdout.

Tookmund commented 4 weeks ago

Thank you for the investigation and suggested solutions!

I'm likely to implement option 1, since Swapspace doesn't have much output, but will probably do a bit more research myself first to understand the implications of this change.