Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Copyright 2015-2021 Rivoreo
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
static pid_t start_shell(const char *command, int rfd, int wfd) {
const char *shell = getenv("SHELL");
if(!shell || !*shell) shell = "/bin/sh";
pid_t pid = fork();
if(pid < 0) return -1;
if(pid) return pid;
if(dup2(rfd, STDIN_FILENO) < 0) {
perror("dup2: rfd");
_exit(1);
}
if(rfd != STDIN_FILENO) close(rfd);
if(dup2(wfd, STDOUT_FILENO) < 0) {
perror("dup2: wfd");
_exit(1);
}
if(wfd != STDOUT_FILENO) close(wfd);
execl(shell, shell, "-c", command, NULL);
perror(shell);
_exit(127);
}
int main(int argc, char **argv) {
if(argc < 3) {
fprintf(stderr, "Usage: %s <shell-command> <shell-command> [<shell-command> ...]\n",
argv[0]);
return -1;
}
int i = 0;
int pipe_fds[argc-1][2];
do {
if(pipe(pipe_fds[i]) < 0) {
perror("pipe");
return 1;
}
} while(++i < argc - 1);
i = 0;
do {
int rfd = pipe_fds[i ? i - 1 : argc - 2][0];
int wfd = pipe_fds[i][1];
if(start_shell(argv[i + 1], rfd, wfd) < 0) {
perror(argv[i + 1]);
return 1;
}
} while(++i < argc - 1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment