From b0518552f19fcf2da3dd265d892205dac23a1b8e Mon Sep 17 00:00:00 2001 From: Anderson Toshiyuki Sasaki Date: Mon, 8 Jun 2020 12:34:53 +0200 Subject: [PATCH] examples: Tolerate incomplete writes in exec example Previously, the exec example would fail if it could not write the whole read buffer to stdout. With this changes, the exec example will be able to write parts of the buffer until the whole buffer is written. This makes the exec example to run when the stdout buffer is small. Signed-off-by: Anderson Toshiyuki Sasaki Reviewed-by: Andreas Schneider --- examples/exec.c | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/examples/exec.c b/examples/exec.c index 4d5e0c1a..7200ddef 100644 --- a/examples/exec.c +++ b/examples/exec.c @@ -8,7 +8,7 @@ int main(void) { ssh_session session; ssh_channel channel; char buffer[256]; - int nbytes; + int rbytes, wbytes, total = 0; int rc; session = connect_ssh("localhost", NULL, 0); @@ -35,15 +35,30 @@ int main(void) { goto failed; } - nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); - while (nbytes > 0) { - if (fwrite(buffer, 1, nbytes, stdout) != (unsigned int) nbytes) { - goto failed; - } - nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); + rbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); + if (rbytes <= 0) { + goto failed; } - if (nbytes < 0) { + do { + wbytes = fwrite(buffer + total, 1, rbytes, stdout); + if (wbytes <= 0) { + goto failed; + } + + total += wbytes; + + /* When it was not possible to write the whole buffer to stdout */ + if (wbytes < rbytes) { + rbytes -= wbytes; + continue; + } + + rbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0); + total = 0; + } while (rbytes > 0); + + if (rbytes < 0) { goto failed; }