我创建了一个 shell,并使用带有空格分隔符的 strtok 解析了从命令提示符获取的输入。我不知道为什么对于特定的命令,ls
或者ls -l
它在为“cp x y”命令工作时不起作用。这是我的代码:
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <assert.h>
void execute(char **argv)
{
int status;
int pid = fork();
if (pid <0) //fork error has happened
{
perror("Can't fork a child process\n");
exit(EXIT_FAILURE);
}
if (pid==0) //It's the child process and can run his task
{
execvp(argv[0],argv);
perror("error");
}
else //pid>0 it's the parent and should wait for the child
{
int status;
// int wc = wait(&status);
// assert(wc != -1);
//while(wait(&status)!=pid)
// ;
wait(NULL); //the way taught in the class
}
}
int main (int argc, char **argv)
{
char input[256];
char *args[256];
char **next = args;
char *temp;
while (1)
{
printf("mysh>");
fgets(input,256,stdin);
input[strlen(input) - 1] = 0;
if (strcmp(argv[0], "exit\n")==0)
exit(EXIT_SUCCESS);
else
{
temp = strtok(input, " ");
while(temp != NULL)
{
printf("%s\n", temp);
*next++ = temp;
temp = strtok(NULL, " ");
}
*next = NULL;
execute(args);
//execvp(args[0],args); //When I put this command here it just runs once though it is in a while loop so we have to use fork!
}
}
return 0;
}
这是它的运行演示:
./basic_shell
mysh>ls
ls
basic_shell basic_shell.c basic_shell.c~ basic_shell_OK.c fork fork.c
mysh>ls
ls
ls: cannot access ls: No such file or directory
mysh>ls
ls
ls: cannot access ls: No such file or directory
ls: cannot access ls: No such file or directory
mysh>ls
ls
ls: cannot access ls: No such file or directory
ls: cannot access ls: No such file or directory
ls: cannot access ls: No such file or directory
当我执行 cp 命令时,它的工作原理如下:
./basic_shell
mysh>cp fork.c fork_cp.c
cp
fork.c
fork_cp.c
mysh>cp fork_cp.c copy_fork.c
cp
fork_cp.c
copy_fork.c
cp: target `copy_fork.c' is not a directory
你能指导我为什么我的外壳表现得有点尴尬和意外吗?