Merge pull request #35 from DevManu-de/dev-redirect-handle
[psh.git] / src / command.c
blobab09487ff993603913214c59e88605ef5b0d88d7
1 /*
2 psh/command.c - psh commands
3 Copyright 2020 Zhang Maiyun
5 This file is part of Psh, P shell.
7 Psh is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Psh is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
25 #include <string.h>
27 #include "command.h"
28 #include "libpsh/xmalloc.h"
30 void free_redirect(struct _psh_redirect *redir)
32 struct _psh_redirect *temp;
33 while (redir != NULL)
35 temp = redir;
36 redir = redir->next;
37 xfree(temp);
38 temp = NULL;
42 /* Malloc a command, enNULL all elements, malloc the first element in argv[] and
43 * a struct _psh_redirect */
44 struct _psh_command *new_command()
46 /* TODO: Remove MAXARG, MAXEACHARG */
47 struct _psh_command *cmd;
48 cmd = xcalloc(1, sizeof(struct _psh_command));
49 /* Setting to '\0' will be used to detect
50 whether an element is used */
51 cmd->argv = xcalloc(MAXARG, P_CS);
52 cmd->argv[0] = xcalloc(MAXEACHARG, P_CS);
53 cmd->rlist = xcalloc(1, sizeof(struct _psh_redirect));
54 return cmd;
57 /* Free a command and its nexts */
58 void free_command(struct _psh_command *cmd)
60 struct _psh_command *temp;
61 while (cmd != NULL)
63 temp = cmd;
64 cmd = cmd->next;
65 free_argv(temp);
66 free_redirect(temp->rlist);
67 xfree(temp);
68 temp = NULL;
72 void free_argv(struct _psh_command *cmd)
74 int count;
75 for (count = 0; count < MAXARG; ++count)
77 if (cmd->argv[count] == NULL)
78 break; /* All args should be freed after here */
79 xfree(cmd->argv[count]);
80 cmd->argv[count] = NULL;
82 xfree(cmd->argv);
83 cmd->argv = NULL;