【发布时间】:2018-03-25 11:28:45
【问题描述】:
我正在尝试在 C 中创建一个 shell,但我被困在使内置函数正常运行的地步。
这是我的代码:
int my_fork(char *line, char **env)
{
/*char *line = arguments entered in getline() (like 'ls' for example)*/
/*char **env = copy of the shell environment*/
int i = 0;
/*Get the PID for forking*/
pid_t pid = getpid();
/*Declaration of one string and one array*/
char *path = malloc(sizeof(char) * 100);
char **tmp = malloc(sizeof(char *) * 7);
/* my_str_to_word_array transform a string into an array of word*/
char **arg = my_str_to_word_array(line);
for (int j = 0; j < 30; j++)
tmp[j] = malloc(sizeof(char) * 100);
/*my_getpath() search and found the PATH variable in the environment*/
path = my_getpath(env);
/*Then, we put the different paths in an array (paths are separated by ':')*/
tmp = my_str_to_word_array(path);
for (int j = 0; j < 7; j++) {
/*my_strcat() put a string after another string*/
/*Here, i put the entered command after all the paths*/
my_strcat(tmp[j], "/");
my_strcat(tmp[j], arg[0]);
/*my_putstr() print a string, here, i try to print all the modified paths*/
my_putstr(tmp[j]);
write (1, "\n", 1);
}
/*i fork and exec the command*/
pid = fork();
execve(tmp[i], arg, env);
/*i wait until the child process end*/
wait(&pid);
return (0);
}
输出给我一个 Segfault 信号,我不知道为什么。 Valgrind 不帮我,我现在不知道该怎么办......
我遇到的错误:“访问不在映射区域 0x0 内”。此错误发生在“my_strlen()”中,该函数用于计算字符串的长度。我已经搜索了为什么会出现此错误,但我不明白,因为在我的字符串末尾,我确定有'\0'。
my_strcat():
char *my_strcat(char *dest, char *src)
{
int i = 0;
int len = my_strlen(dest);
for (; src[i] != '\0'; i++)
dest[len + i] = src[i];
i++;
dest[len + i] = '\0';
return (dest);
}
my_strlen():
int my_strlen (char *str)
{
int i = 0;
while (str[i])
i++;
return (i);
}
所以,总而言之,我想让内置函数正常运行,我在 my_strlen() 中有一个错误,这不是我唯一的错误,但现在,让我们关注这个。
【问题讨论】:
-
您可能应该添加使用
my_strlen的my_strcat。看起来您访问了不应该访问的内容。 -
是的,我已经编辑了上一篇文章。谢谢。
-
最后,
my_str_to_word_array呢?还要在您的程序中打印path(在my_getpath之后)并在此处发布结果,以确保它符合您的预期,以便我们了解您正在处理什么以及如何处理。 -
只是一个简短的说明,应该有零理由为 shell 内置调用
exec。除非您计划同时运行它,否则您甚至可能不需要fork。 -
我正在用 C 编写一个 minishell,我必须让像 ls 这样的内置函数在其中工作。这是我学校的一个项目,我被授权只能使用 fork 和 execve能够做到这一点,我没有找到其他解决方案...... -_-