1
0
mirror of https://git.libssh.org/projects/libssh.git synced 2025-07-29 13:01:13 +03:00

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 b0518552f1)
This commit is contained in:
Anderson Toshiyuki Sasaki
2020-06-08 12:34:53 +02:00
parent 1da78553dc
commit 039054ea6e

View File

@ -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;
}