aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnderson Toshiyuki Sasaki <ansasaki@redhat.com>2020-06-08 12:34:53 +0200
committerAndreas Schneider <asn@cryptomilk.org>2020-06-22 13:58:52 +0200
commitb0518552f19fcf2da3dd265d892205dac23a1b8e (patch)
treea2b69970501875c631f322e16a449b870d18eb4d
parent1694606e12d8950b003ff86248883732ef05e00c (diff)
downloadlibssh-b0518552f19fcf2da3dd265d892205dac23a1b8e.tar.gz
libssh-b0518552f19fcf2da3dd265d892205dac23a1b8e.tar.xz
libssh-b0518552f19fcf2da3dd265d892205dac23a1b8e.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>
-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;
}