C 我所构建的shell的权限被拒绝
我创建了一个shell,并使用strtok和空格分隔符解析了从命令提示符获取的输入。我不知道为什么对于像C 我所构建的shell的权限被拒绝,c,shell,process,argv,fork,C,Shell,Process,Argv,Fork,我创建了一个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.
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;
}
当我执行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
你能告诉我为什么我的shell表现得有点笨拙和出人意料吗?你有两次呼叫
fork
int pid = fork();
if ((pid = fork()) <0)
要删除
\n
您需要两次调用fork
int pid = fork();
if ((pid = fork()) <0)
要删除
\n
谢谢您抓到fork()这个东西。对于无效的东西,你说的不起作用,我有以下错误:fgets(input,256,stdin);stdin[strlen(stdin)-1]=0<代码>basic_shell.c:在函数'main'中:basic_shell.c:48:警告:从不兼容的指针类型/usr/include/string传递'strlen'的参数1.h:399:注意:应为'const char*',但参数的类型为'struct_IO_FILE*'basic_shell.c:48:错误:从类型分配给'struct_IO_FILE'时,类型不兼容“int”My bad,它应该是input
,而不是stdin
。改写了答案。是的,应该改两次。我必须去睡觉:)谢谢,所以我有这个问题:mysh>ls-ls-ls-basic\u-shell-basic\u-shell.c~ code.c?fork.c mysh.c pa strtok basic_shell.c basic_shell_OK.c fork mysh new_shell.c?pointer_array.c strtok.c mysh>ls ls:无法访问ls:没有这样的文件或目录
感谢您捕捉到fork()的内容。对于无效的东西,你说的不起作用,我有以下错误:fgets(input,256,stdin);stdin[strlen(stdin)-1]=0<代码>basic_shell.c:在函数'main'中:basic_shell.c:48:警告:从不兼容的指针类型/usr/include/string传递'strlen'的参数1.h:399:注意:应为'const char*',但参数的类型为'struct_IO_FILE*'basic_shell.c:48:错误:从类型分配给'struct_IO_FILE'时,类型不兼容“int”My bad,它应该是input
,而不是stdin
。改写了答案。是的,应该改两次。我必须去睡觉:)谢谢,所以我有这个问题:mysh>ls-ls-ls-basic\u-shell-basic\u-shell.c~ code.c?fork.c mysh.c pa strtok basic_shell.c basic_shell_OK.c fork mysh new_shell.c?pointer_array.c strtok.c mysh>ls ls:无法访问ls:没有这样的文件或目录
input[strlen(input) - 1] = 0;