Fixed a bug in hush

This commit is contained in:
Dan Hirsch 2012-05-26 13:13:56 +02:00
parent f462d5feb3
commit d7ba53b3b1

View file

@ -1,9 +1,11 @@
// -*- c-basic-offset: 8; tab-width: 8 -*-
#include <unistd.h> #include <unistd.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <string.h>
int main (int argc, char** argv) { int main (int argc, char** argv) {
// Argv[1] is the message // Argv[1] is the message
@ -11,7 +13,12 @@ int main (int argc, char** argv) {
// the rest are passed to the child // the rest are passed to the child
if (argc < 3) return 1; if (argc < 3) return 1;
printf ("\x1b[1;32m*\x1b[0m %s...", argv[1]); printf ("\x1b[1;32m*\x1b[0m %s...", argv[1]);
char cbuf[4096];
char *cbuf = malloc(4096);
size_t cbuf_cap = 4096;
size_t cbuf_len = 0;
char cbuf2[4096];
argc-=2; argc-=2;
argv+=1; argv+=1;
for (int i = 0; i < argc; i++) for (int i = 0; i < argc; i++)
@ -40,24 +47,27 @@ int main (int argc, char** argv) {
if (cols1) { cols = atoi(cols1); } else { cols = 80; } if (cols1) { cols = atoi(cols1); } else { cols = 80; }
close(fd[0]); close(fd[0]);
int delta = 1; int delta = 1;
int ct = 0;
while (delta != 0) { while (delta != 0) {
delta = read (fd[1], cbuf+ct, 4096-ct); delta = read (fd[1], cbuf2, 4096);
ct+= delta; while ((cbuf_len + delta) >= cbuf_cap)
cbuf = realloc(cbuf, cbuf_cap *= 2);
memcpy(cbuf + cbuf_len, cbuf2, delta);
cbuf_len += delta;
} }
cbuf[ct] = 0;
int status; int status;
wait(&status); wait(&status);
fflush (NULL); fflush (NULL);
if (status) { if (status) {
fprintf (stderr, "\x1b[%dG\x1b[1;34m[\x1b[1;31m!!\x1b[1;34m]\x1b[0m\n", cols-4); fprintf (stderr, "\x1b[%dG\x1b[1;34m[\x1b[1;31m!!\x1b[1;34m]\x1b[0m\n", cols-4);
} else if (ct) { } else if (cbuf_len) {
fprintf (stderr, "\x1b[%dG\x1b[1;34m[\x1b[0;33mWW\x1b[1;34m]\x1b[0m\n", cols-4); fprintf (stderr, "\x1b[%dG\x1b[1;34m[\x1b[0;33mWW\x1b[1;34m]\x1b[0m\n", cols-4);
} else { } else {
fprintf (stderr, "\x1b[%dG\x1b[1;34m[\x1b[1;32mOK\x1b[1;34m]\x1b[0m\n", cols-4); fprintf (stderr, "\x1b[%dG\x1b[1;34m[\x1b[1;32mOK\x1b[1;34m]\x1b[0m\n", cols-4);
} }
fflush (NULL); fflush (NULL);
printf ("%s", cbuf); write(2, cbuf, cbuf_len);
free(cbuf);
fflush (NULL); fflush (NULL);
return WEXITSTATUS(status); return WEXITSTATUS(status);
} }