我必须在C中重新编码一个shell,当我尝试这样做时,例如,ls | ls | ls ; exit
,我有一个Segmentation错误。 (malloc.c:3630:_int_malloc:断言`(无符号长)(大小)> =(无符号长)(nb)'失败。
中止)
我的退出是在ls | ls | ls
结束之前运行的,但如果只有一个管道工作。
如果您有任何想法,或者您想了解更多信息,请告诉我。
这里是exec(多)管道的功能:
void exec_pipe(char *multi)
{
char **cmd;
int *pfd;
int pn;
int status;
int i;
pfd = NULL;
i = 0;
pn = count_pipe(multi);
cmd = my_str_to_wordtabpipe(multi);
pfd = init_pfd(pfd, pn);
exec_pipe_cmd(pfd, pn, cmd);
close_pfd(pfd, pn);
while (i < pn + 1)
{
wait(&status);
i++;
}
destroy_tabstr(&cmd);
free(pfd);
}
void exec_pipe_cmd(int *pfd, int pn, char **cmd)
{
int i;
int j;
i = 0;
j = 0;
while (cmd[i])
{
if (cmd[i][0] == '~')
if (!(cmd[i] = put_home(cmd[i])))
my_e_printf("No $HOME variable set.\n");
if (cmd[i])
cmd[i] = get_alias(cmd[i]);
fork_pipe(&cmd[i], pfd, pn, j);
j += 2;
i++;
}
}
void dup_pipe(char **cmd, int *pfd, int j)
{
if (*(cmd + 1))
if (dup2(pfd[j + 1], 1) < 0)
exit(-1);
if (j != 0)
if (dup2(pfd[j - 2], 0) < 0)
exit(-1);
}
void fork_pipe(char **cmd, int *pfd, int pn, int j)
{
char **tmp;
pid_t pid;
char *path;
tmp = my_str_to_wordtab(cmd[0]);
if ((pid = fork()) == 0)
{
path = get_cmd_path(tmp[0]);
if (my_strcmp(path, tmp[0]) == 0 && path[0] != '.'
&& path[0] != '~' && path[0] != '/')
path = NULL;
dup_pipe(cmd, pfd, j);
close_pfd(pfd, pn);
if (exec_builtins(tmp))
exit(0);
else if (!path || execve(path, tmp, g_env) == -1)
{
my_e_printf("%s: Command not found.\n", tmp[0]);
exit(-1);
}
}
destroy_tabstr(&tmp);
}
int count_pipe(char *str)
{
int k;
int i;
i = 0;
k = 0;
while (str[i])
{
if (str[i] == '|')
k++;
i++;
}
return (k);
}
int *init_pfd(int *pfd, int pn)
{
int i;
i = 0;
if ((pfd = malloc(sizeof(int) * (pn * 2))) == NULL)
exit(-1);
while (i < pn)
{
if (pipe(pfd + i * 2) < 0)
my_printf("An error occured when pipe creation\n");
i++;
}
return (pfd);
}
void close_pfd(int *pfd, int pn)
{
int i;
i = 0;
while (i < 2 * pn)
{
close(pfd[i]);
i++;
}
}
int count_pipe(char *str)
{
int k;
int i;
i = 0;
k = 0;
while (str[i])
{
if (str[i] == '|')
k++;
i++;
}
return (k);
}
int *init_pfd(int *pfd, int pn)
{
int i;
i = 0;
if ((pfd = malloc(sizeof(int) * (pn * 2))) == NULL)
exit(-1);
while (i < pn)
{
if (pipe(pfd + i * 2) < 0)
my_printf("An error occured when pipe creation\n");
i++;
}
return (pfd);
}
void close_pfd(int *pfd, int pn)
{
int i;
i = 0;
while (i < 2 * pn)
{
close(pfd[i]);
i++;
}
}