首页 > 解决方案 > 我的程序仅在我声明一个额外的数组时才有效

问题描述

我正在为一个类构建一个简单的外壳。我的 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;
}

标签: cshellubuntuunixgcc

解决方案


  1. waitpid(child)似乎错了。尝试:
// ...
#include <sys/wait.h>
// ...
    pid_t child;
    int wstatus;
// ...
            else {
                wait(&wstatus);
  1. envp未声明。尝试:
// ...
int main(int argc, char *argv[], char *envp[]) {
// ...
  1. 处理中的一个错误argv1。尝试:
// ...
            if (child == 0) {
                argv1[args] = 0;
                execve(command, argv1, envp); // why use &argv1[0] ?
// ...

我认为(3)是罪魁祸首。

使用不同级别的优化(-O等)进行编译似乎会影响错误是否+1导致问题。


推荐阅读