aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnderson Toshiyuki Sasaki <ansasaki@redhat.com>2020-06-08 12:34:53 +0200
committerAnderson Toshiyuki Sasaki <ansasaki@redhat.com>2020-06-23 19:57:55 +0200
commit039054ea6e6207432150e6542efc38eada0b2e64 (patch)
tree7b1a7890ddeabb6eb24a9fafd421c9e1095a9738
parent1da78553dce8a112ebdddb68ab84f25e8f1152c5 (diff)
downloadlibssh-039054ea6e6207432150e6542efc38eada0b2e64.tar.gz
libssh-039054ea6e6207432150e6542efc38eada0b2e64.tar.xz
libssh-039054ea6e6207432150e6542efc38eada0b2e64.zip
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 <ansasaki@redhat.com> Reviewed-by: Andreas Schneider <asn@cryptomilk.org> (cherry picked from commit b0518552f19fcf2da3dd265d892205dac23a1b8e)
-rw-r--r--examples/exec.c29
1 files changed, 22 insertions, 7 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) {
+ rbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
+ if (rbytes <= 0) {
+ goto failed;
+ }
+
+ do {
+ wbytes = fwrite(buffer + total, 1, rbytes, stdout);
+ if (wbytes <= 0) {
goto failed;
}
- nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
- }
- if (nbytes < 0) {
+ 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;
}