pexec

execute a program from standard input
git clone git://git.2f30.org/pexec
Log | Files | Refs

commit 3b39dcfbbdcc324415e8991dd2d5c6619b8066c8
parent 33677e7d503a945df47430563753fcd530975690
Author: sin <sin@2f30.org>
Date:   Fri, 23 Mar 2018 15:56:22 +0000

Move pexec code into its own function

Diffstat:
Mpexec.c | 50+++++++++++++++++++++++++++++---------------------
1 file changed, 29 insertions(+), 21 deletions(-)

diff --git a/pexec.c b/pexec.c @@ -32,12 +32,6 @@ char *argv0; -static int -memfd_create(const char *name, unsigned int flags) -{ - return syscall(__NR_memfd_create, name, flags); -} - static ssize_t xread(int fd, void *buf, size_t nbytes) { @@ -78,6 +72,33 @@ xwrite(int fd, const void *buf, size_t nbytes) return total; } +static int +memfd_create(const char *name, unsigned int flags) +{ + return syscall(__NR_memfd_create, name, flags); +} + +void +pexec(int ifd, char *argv[], char *envp[]) +{ + char buf[BUFSIZ]; + ssize_t n; + int fd; + + fd = memfd_create(argv[0], 0); + if (fd < 0) + err(1, "memfd_create"); + + if (fchmod(fd, 0755) < 0) + err(1, "fchmod"); + + while ((n = xread(ifd, buf, BUFSIZ)) > 0) + xwrite(fd, buf, n); + + if (fexecve(fd, argv, envp) < 0) + err(1, "fexecve"); +} + static void usage(void) { @@ -89,9 +110,7 @@ int main(int argc, char *argv[]) { char *envp[] = { NULL }; - char buf[BUFSIZ]; - ssize_t n; - int fd, iflag = 0; + int iflag = 0; ARGBEGIN { case 'i': @@ -104,18 +123,7 @@ main(int argc, char *argv[]) if (argc == 0) usage(); - fd = memfd_create(argv[0], 0); - if (fd < 0) - err(1, "memfd_create"); - - if (fchmod(fd, 0755) < 0) - err(1, "fchmod"); - - while ((n = xread(STDIN_FILENO, buf, BUFSIZ)) > 0) - xwrite(fd, buf, n); - extern char **environ; - if (fexecve(fd, argv, iflag ? envp : environ) < 0) - err(1, "fexecve"); + pexec(STDIN_FILENO, argv, iflag ? envp : environ); /* unreachable */ }