aboutsummaryrefslogtreecommitdiff
path: root/examples/exec.c
diff options
context:
space:
mode:
Diffstat (limited to 'examples/exec.c')
-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;
}