gpt4 book ai didi

c - 为什么 "Cat"在我构建的 C-shell 中不起作用?

转载 作者:行者123 更新时间:2023-11-30 17:42:43 24 4
gpt4 key购买 nike

例如,当我输入 Cat hello.txt 时,它只会读取 Cat 并启动几乎一个内部循环,并且我输入的所有内容都会重复。诸如“ls”之类的单个命令可以正常工作。我认为这与存在空间有关。我究竟做错了什么?谢谢

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define MAX_LENGTH 1024
#define DELIMS " \t\r\n"
int main(int argc, char *argv[])
{
char line[MAX_LENGTH];
int loop = 1;
int pid;
int status;
char *cmd;

while (1)
{
status = 0;

printf("Ben$ ");
// printf("%d\n",pid );
if (!fgets(line, MAX_LENGTH, stdin))
{
loop = 0;
break;
}
pid = fork();

if (pid == 0)
{

if ((cmd = strtok(line, DELIMS)))
{
// Clear errors
errno = 0;

if (strcmp(cmd, "cd") == 0)
{
char *arg = strtok(0, DELIMS);

if (!arg)
fprintf(stderr, "cd missing argument.\n");
else
chdir(arg);

}
else if (strcmp(cmd, "exit") == 0)
{
_Exit(3);
printf("should have exited\n");

}
else
{
char *name[] = {
"/bin/bash",
"-c",
line, NULL
};
execvp(name[0], name);

}

if (errno)
perror("Command failed");
}
}
else
{
// printf("%d\n",pid );
waitpid(pid, &status, 0);

if (status != 0)
{
break;
}

}

}

return 0;
}

最佳答案

您调用strtok ,它通过用 '\0' 替换第一个分隔符来“分解”字符串。 。所以,如果line strtok 之前有这个调用:

{ 'c', 'a', 't', ' ', 'h', 'e', 'l', 'l', 'o',
'.', 't', 'x', 't', '\n', '\0', <junk...> }

然后里面有这个:

{ 'c', 'a', 't', '\0', 'h', 'e', 'l', 'l', 'o',
'.', 't', 'x', 't', '\n', '\0', <junk...> }

因此,您调用 "/bin/bash""-c" , "cat" , NULL .

旁白:变量 loop没有经过测试;在一个 shell 中,cdexit命令必须在父级中实现,而不是在fork之后实现称呼;正如 @shanet 指出的,你可以 execvp直接命令(对于非管道,无重定向)命令,尽管您必须首先拆分参数。 (真正的 shell 也需要进行自己的文件和管道处理,但显然这是稍后的事情。:-) )

关于c - 为什么 "Cat"在我构建的 C-shell 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20436904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com