From 04c490f3c9375ce4a8f38b3b4bedc3ed7b986cf0 Mon Sep 17 00:00:00 2001 From: Curtis McEnroe Date: Sat, 17 Sep 2016 00:35:22 -0400 Subject: Factor out spawn in pbd --- .bin/pbd.c | 49 +++++++++++++++++++------------------------------ 1 file changed, 19 insertions(+), 30 deletions(-) (limited to '.bin/pbd.c') diff --git a/.bin/pbd.c b/.bin/pbd.c index 713800d4..3f924f2c 100755 --- a/.bin/pbd.c +++ b/.bin/pbd.c @@ -1,8 +1,7 @@ #if 0 -exec clang -Weverything $@ -o $(dirname $0)/pbd $0 +exec clang -Weverything -Wno-missing-prototypes $@ -o $(dirname $0)/pbd $0 #endif -#include #include #include #include @@ -12,6 +11,22 @@ exec clang -Weverything $@ -o $(dirname $0)/pbd $0 #include #include +void spawn(const char *cmd, int child_fd, int parent_fd) { + pid_t pid = fork(); + if (pid < 0) err(EX_OSERR, "fork"); + + if (pid) { + if (waitpid(pid, NULL, 0) < 0) + err(EX_OSERR, "waitpid"); + // TODO: Check child status. + } else { + if (dup2(parent_fd, child_fd) < 0) + err(EX_OSERR, "dup2"); + if (execlp(cmd, cmd) < 0) + err(EX_OSERR, "execlp"); + } +} + int main() { int server = socket(PF_INET, SOCK_STREAM, 0); if (server < 0) err(EX_OSERR, "socket"); @@ -32,39 +47,13 @@ int main() { int client = accept(server, NULL, NULL); if (client < 0) err(EX_OSERR, "accept"); - pid_t pid_paste = fork(); - if (pid_paste < 0) err(EX_OSERR, "fork"); - - if (pid_paste) { - if (waitpid(pid_paste, NULL, 0) < 0) - warn("waitpid"); - // TODO: Check child status. - } else { - if (dup2(client, STDOUT_FILENO) < 0) - err(EX_OSERR, "dup2"); - if (execlp("pbpaste", "pbpaste") < 0) - err(EX_OSERR, "execlp"); - } + spawn("pbpaste", STDOUT_FILENO, client); uint8_t x; ssize_t peek = recv(client, &x, 1, MSG_PEEK); if (peek < 0) err(EX_IOERR, "recv"); - if (peek) { - pid_t pid_copy = fork(); - if (pid_copy < 0) err(EX_OSERR, "fork"); - - if (pid_copy) { - if (waitpid(pid_copy, NULL, 0) < 0) - warn("waitpid"); - // TODO: Check child status. - } else { - if (dup2(client, STDIN_FILENO) < 0) - err(EX_OSERR, "dup2"); - if (execlp("pbcopy", "pbcopy") < 0) - err(EX_OSERR, "execlp"); - } - } + if (peek) spawn("pbcopy", STDIN_FILENO, client); if (close(client) < 0) warn("close"); } -- cgit 1.4.1