gpt4 book ai didi

c - 简单的 Linux Shell - execvp() 失败

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:20 28 4
gpt4 key购买 nike

我需要一些关于类的简单 shell 的帮助,我担心我不太了解 execvp() 函数的工作原理。

shell 做的不多,不支持管道、重定向、脚本或任何类似的东西。它只读取一个命令,读入选项(命令作为选项[0]),然后 fork 。

它工作了几次,然后开始给我关于无法找到命令的错误。此处发布的其他类似问题与管道或重定向有关。

请原谅菜鸟代码,它不是很漂亮,但我希望它是清晰的:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

#define OPT_AMT 10

const size_t SIZE = 256;
int i = 0;
int o = 0;

int main(void) {

// initializing data

int exit = 0;
char cwd[SIZE];
char cmd[SIZE];
char input[SIZE * OPT_AMT];
char *opt[OPT_AMT];
getcwd(cwd, SIZE);

// main loop

while (exit == 0) {
// reset everything
o = 1;
i = 0;
cmd[0] = "\0";
while (i < OPT_AMT) {
opt[i++] = "\0";
}

// get input
printf("%s $ ", cwd);
scanf("%s", cmd);
gets(input);
opt[0] = cmd;

char *t = strtok(input, " ");
while (t != NULL) {
opt[o++] = t;
t = strtok(NULL, " ");
}

// if exit, exit
if (strcmp(cmd, "exit") == 0) {
exit = 1;
}
// else fork and execute
else {
pid_t pID = fork();

if (pID == 0) { // child process
execvp(cmd, opt);
} else if (pID < 0) { // failed to fork
printf("\nFailed to fork\n");
} else { // parent process
wait(0);
}
}
}

// cleanup

printf("\nFinished! Exiting...\n");
return 0;
}

有什么明显的错误吗?我最近添加了退出条件和重置选项数组。

另外,这是我的第一个问题,所以请提醒我我可能违反的任何规则。

最佳答案

对于初学者来说,这

cmd[0] = "\0";

应该是

cmd[0] = '\0';

听听编译器的警告。

要启用它们,请使用选项 -Wall -Wextra -pedantic(对于 gcc)。


此外,您最好将 opt 的元素初始化为指向“无”,即 NULL,但指向文字 "\0":

    while (i < OPT_AMT) {
opt[i++] = NULL;
}

作为execvp()要求 opt 是一个以 NULL 结尾的 C-“字符串”数组(感谢 Paul 提及/措辞相关背景)。


另外^2:不要使用gets(),因为它是邪恶的,甚至不再是C 标准的一部分。而不是

gets(input);

使用

fgets(input, sizeof input, stdin);

gets() 让用户轻松溢出传递的(输入)缓冲区。 (在没有 Paul 的情况下我想到了这个,顺便说一句……;-))

关于c - 简单的 Linux Shell - execvp() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26950228/

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