c - 我的程序仅在我声明一个额外的数组时才有效
问题描述
我正在为一个类构建一个简单的外壳。我的 shell 目录中有两个程序,分别称为“alomundo”和“echo”。"./alomundo" 打印 "Alo mundo!" 到控制台,./echo 使用给定的 args 执行 ubuntu echo。问题是我的程序只有在我声明 char aux[15] 时才有效。请注意,我不会无缘无故地使用它。任何人都可以理解有什么问题吗?
一个示例输入是
./shell 回声 ab,alomundo,回声 abc
正确的输出是
抗体
天哪!
美国广播公司
未声明 char aux[15] 时的输出只是:
天哪!
美国广播公司
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char aux[15]; // <---- GRRRR
int child; // will hold the childs PID after fork()
int i = 0; // counter to loop through this mains *argv[]
int t = 0; // auxiliar counter to loops
int arg_len; // will hold the length of each argument while the argument is being processed
int args = 0; // current number of arguments in the argv1 vector
int send = 0; // boolean to check if the command should be executed in the current loop or not
char *command; // string to hold the main command name
char *argv1[15]; // vector to hold the arguments passed to execve
for(i=1; i<argc; i++) {
arg_len = strlen(argv[i]);
argv1[args] = (char *) malloc(sizeof(char) * 25);
for(t=0; t<25; t++) {
argv1[args][t] = '\0';
}
if (argv[i][arg_len-1] == ',') {
argv[i][arg_len-1] = '\0';
send = 1;
}
else if (i == (argc-1)) {
send = 1;
}
if (args == 0) {
command = (char *) malloc(sizeof(char) * 255);
strcpy(command, "./");
strcpy(argv1[args], "./");
strcat(command, argv[i]);
}
strcat(argv1[args], argv[i]);
args++;
if (send) {
child = fork();
if (child == 0) {
argv1[args+1] = 0;
execve(command, &argv1[0], envp);
return 0;
}
else {
waitpid(child);
free(command);
for (t=0; t<args; t++) {
free(argv1[t]);
argv1[t] = NULL;
}
args = 0;
send = 0;
}
}
}
return 0;
}
解决方案
waitpid(child)
似乎错了。尝试:
// ...
#include <sys/wait.h>
// ...
pid_t child;
int wstatus;
// ...
else {
wait(&wstatus);
envp
未声明。尝试:
// ...
int main(int argc, char *argv[], char *envp[]) {
// ...
- 处理中的一个错误
argv1
。尝试:
// ...
if (child == 0) {
argv1[args] = 0;
execve(command, argv1, envp); // why use &argv1[0] ?
// ...
我认为(3)是罪魁祸首。
使用不同级别的优化(-O
等)进行编译似乎会影响错误是否+1
导致问题。
推荐阅读
- c# - 使用外部加速度计的 C# 振动传感器
- ruby-on-rails - 将 Rails 5.1 升级到 5.2,找不到 gem 版本,但似乎满足了所有要求
- c++ - Visual Studio 2017 命令行构建速度比 IDE 慢
- python - 从文件中的列获取数据
- node.js - 在各种事件下自动打开串口并记录数据
- javascript - 在 reactjs 前端使用 fetch 从 express 服务器获取 mongodb 数据
- android - Android Studio - 即使在“修复”问题后自动导入也不起作用
- c# - 试图将我的流保存在我的视图模型中
- ubuntu - wsl 2 ubuntu mariadb .my.cnf.42' 被忽略
- browser - 在插件中使用假视频我不能在赛普拉斯的测试流程中使用两个视频