aboutsummaryrefslogtreecommitdiffstats
path: root/src/command.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/command.c')
-rw-r--r--src/command.c52
1 files changed, 45 insertions, 7 deletions
diff --git a/src/command.c b/src/command.c
index 73a2027..ea198ec 100644
--- a/src/command.c
+++ b/src/command.c
@@ -8,9 +8,28 @@
#include <stdio.h>
#include <unistd.h>
+command *create_command() {
+ command *cmd = malloc(sizeof(command));
+ if (!cmd) {
+ return NULL;
+ }
+
+ cmd->command = NULL;
+ memset(cmd->args, 0, sizeof(char*));
+ cmd->pipe[0] = -1;
+ cmd->pipe[1] = -1;
+ cmd->read_pipe = NULL;
+ cmd->infile = NULL;
+ cmd->outfile = NULL;
+ cmd->next = NULL;
+ cmd->pid = 0;
+
+ return cmd;
+}
+
command *commands_from_tokens(token *parsed_cmdstr, size_t *cnt) {
- command *cmd_head = calloc(1, sizeof(command));
+ command *cmd_head = create_command();
command *cmd = cmd_head;
size_t arg_cnt = 1;
@@ -33,7 +52,7 @@ command *commands_from_tokens(token *parsed_cmdstr, size_t *cnt) {
cmd->outfile = tkn->text;
}
} else if (tkn->type == TKN_PIPE) {
- cmd->next = calloc(1, sizeof(command));
+ cmd->next = create_command();
cmd->next->read_pipe = cmd->pipe;
cmd = cmd->next;
}
@@ -50,7 +69,10 @@ void print_commands(FILE *file, command *cmds) {
for (size_t i=0; i<MAX_ARGUMENT_CNT; i++) {
fprintf(file, "%s ", cmd->args[i]);
}
- fprintf(file, "\n\tInfile: %s\n\tOutfile: %s\n", cmd->infile, cmd->outfile);
+ fprintf(file, "\n\tInfile: %s\n\tOutfile: %s\n\tInput Pipe: %p\n\tPid:%d\n", cmd->infile, cmd->outfile, cmd->read_pipe, cmd->pid);
+ if (cmd->read_pipe) {
+ fprintf(file, "\tInput Pipe: %d\n", *cmd->read_pipe);
+ }
}
}
@@ -70,13 +92,15 @@ pid_t execute_command(command *cmd) {
pid_t res = fork();
if (res == 0) {
+ int fdi = -1, fdo = -1;
+
if (cmd->infile) {
if (!freopen(cmd->infile, "r", stdin)) {
perror("Could not open input file");
exit(EXIT_FAILURE);
}
- } else if (cmd->read_pipe) {
- dup2(*(cmd->read_pipe), STDIN_FILENO);
+ } else if (cmd->read_pipe && *cmd->read_pipe >= 0) {
+ fdi = dup2(*(cmd->read_pipe), STDIN_FILENO);
close(*(cmd->read_pipe));
}
@@ -86,16 +110,30 @@ pid_t execute_command(command *cmd) {
exit(EXIT_FAILURE);
}
} else if (cmd->next) {
- dup2(cmd->pipe[1], STDOUT_FILENO);
+ fdo = dup2(cmd->pipe[1], STDOUT_FILENO);
+ }
+
+ fprintf(stderr, "In command:\n");
+ fprintf(stderr, "STDIN: %d\tSTDOUT: %d\n", fdi, fdo);
+
+
+ if (cmd->pipe[0] >= 0) {
+ close(cmd->pipe[0]);
+ cmd->pipe[0] = -1;
+ }
+
+ if (cmd->pipe[1] >= 0) {
close(cmd->pipe[1]);
+ cmd->pipe[1] = -1;
}
- int res = execvp(cmd->command, cmd->args);
+ execvp(cmd->command, cmd->args);
perror("Could not run command");
exit(EXIT_FAILURE);
} else if (res < 0) {
perror("Could not run command");
+ return -1;
}
cmd->pid = res;