Fix !calc: pipe expression to bc stdin
bc reads from stdin but the child process never wrote the expression to it, causing empty output. Added a second pipe to feed the expression into bc's stdin before reading the result from stdout.
This commit is contained in:
parent
c554ed60d9
commit
8dd4e35332
1 changed files with 16 additions and 13 deletions
29
zynk.c
29
zynk.c
|
|
@ -2567,26 +2567,29 @@ static int cmd_calc(Session *s, const char *msg, const char *reply_target, const
|
|||
irc_msg(s, reply_target, "Usage: !calc <expression> (e.g. !calc 2+2, !calc (3*7)+1)");
|
||||
return 1;
|
||||
}
|
||||
int fd[2];
|
||||
if (pipe(fd) < 0) { irc_msg(s, reply_target, "Calc: internal error"); return 1; }
|
||||
int in_pipe[2], out_pipe[2];
|
||||
if (pipe(in_pipe) < 0 || pipe(out_pipe) < 0) { irc_msg(s, reply_target, "Calc: internal error"); return 1; }
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) { close(fd[0]); close(fd[1]); irc_msg(s, reply_target, "Calc: fork failed"); return 1; }
|
||||
if (pid < 0) { close(in_pipe[0]); close(in_pipe[1]); close(out_pipe[0]); close(out_pipe[1]); irc_msg(s, reply_target, "Calc: fork failed"); return 1; }
|
||||
if (pid == 0) {
|
||||
close(fd[0]);
|
||||
dup2(fd[1], STDOUT_FILENO);
|
||||
dup2(fd[1], STDERR_FILENO);
|
||||
close(fd[1]);
|
||||
int dn = open("/dev/null", O_WRONLY);
|
||||
if (dn >= 0) { dup2(dn, STDERR_FILENO); close(dn); }
|
||||
close(in_pipe[1]);
|
||||
close(out_pipe[0]);
|
||||
dup2(in_pipe[0], STDIN_FILENO);
|
||||
close(in_pipe[0]);
|
||||
dup2(out_pipe[1], STDOUT_FILENO);
|
||||
close(out_pipe[1]);
|
||||
execlp("bc", "bc", "-l", (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
close(fd[1]);
|
||||
close(in_pipe[0]);
|
||||
close(out_pipe[1]);
|
||||
write(in_pipe[1], rest, strlen(rest));
|
||||
write(in_pipe[1], "\n", 1);
|
||||
close(in_pipe[1]);
|
||||
char buf[512], tmp[256];
|
||||
size_t len = 0;
|
||||
ssize_t n;
|
||||
while ((n = read(fd[0], tmp, sizeof tmp - 1)) > 0) {
|
||||
tmp[n] = 0;
|
||||
while ((n = read(out_pipe[0], tmp, sizeof tmp - 1)) > 0) {
|
||||
size_t avail = sizeof buf - 1 - len;
|
||||
if (avail > 0) {
|
||||
size_t copy = (size_t)n < avail ? (size_t)n : avail;
|
||||
|
|
@ -2594,7 +2597,7 @@ static int cmd_calc(Session *s, const char *msg, const char *reply_target, const
|
|||
len += copy;
|
||||
}
|
||||
}
|
||||
close(fd[0]);
|
||||
close(out_pipe[0]);
|
||||
int status;
|
||||
waitpid(pid, &status, 0);
|
||||
while (len > 0 && (buf[len-1] == '\n' || buf[len-1] == '\r')) len--;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue