Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements to $&here w/r/t forking #160

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 44 additions & 16 deletions prim-io.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include "gc.h"
#include "prim.h"

#include <limits.h>

static const char *caller;

static int getnumber(const char *s) {
Expand Down Expand Up @@ -157,32 +159,58 @@ static int pipefork(int p[2], int *extra) {
return pid;
}

REDIR(here) {
int pid, p[2];
List *doc, *tail, **tailp;
PRIM(here) {
int fd, doclen, p[2], status, ticket = UNREGISTERED;
volatile int pid = -1;
List *tail, **tailp;

assert(list != NULL);
for (tailp = &list; (tail = *tailp)->next != NULL; tailp = &tail->next)
caller = "$&here";
if (length(list) < 2)
argcount("%here fd [word ...] cmd");

fd = getnumber(getstr(list->term));
Ref(List *, lp, list->next);
for (tailp = &lp; (tail = *tailp)->next != NULL; tailp = &tail->next)
;
doc = (list == tail) ? NULL : list;
*tailp = NULL;

if ((pid = pipefork(p, NULL)) == 0) { /* child that writes to pipe */
Ref(char *, doc, (lp == tail) ? NULL : str("%L", lp, ""));
doclen = strlen(doc);

Ref(List *, cmd, tail);
#ifdef PIPE_BUF
if (doclen <= PIPE_BUF) {
pipe(p);
ewrite(p[1], doc, doclen);
} else
#endif
if ((pid = pipefork(p, NULL)) == 0) { /* child that writes to pipe */
close(p[0]);
fprint(p[1], "%L", doc, "");
ewrite(p[1], doc, doclen);
esexit(0);
}

close(p[1]);
*srcfdp = p[0];
return tail;
}
ticket = defer_mvfd(TRUE, p[0], fd);

PRIM(here) {
caller = "$&here";
if (length(list) < 2)
argcount("%here fd [word ...] cmd");
return redir(redir_here, list, evalflags);
ExceptionHandler
lp = eval(cmd, NULL, evalflags);
CatchException (e)
undefer(ticket);
close(p[0]);
if (pid > 0)
ewaitfor(pid);
throw(e);
EndExceptionHandler

undefer(ticket);
close(p[0]);
if (pid > 0) {
status = ewaitfor(pid);
printstatus(0, status);
}
RefEnd2(cmd, doc);
RefReturn(lp);
}

PRIM(pipe) {
Expand Down