【问题标题】:String bug in my_shell programmy_shell 程序中的字符串错误
【发布时间】:2017-02-23 21:35:12
【问题描述】:

我正在尝试创建一个简单的 shell 程序来执行输入中指定的程序。主要有两个功能:scanner()(使用strtok将输入拆分为token)和execute()(fork进程并执行程序)。

不幸的是它不起作用...我尝试在scanner() 的末尾和execute() 的开头打印string[0]。第一次输出是正确的,但第二次string[] 似乎被修改为随机数序列,所以execvp() 不起作用...

我真的不知道为什么string[] 的值会发生变化,可能是一个非常愚蠢的错误,但我看不到。我真的需要你的帮助!感谢您的建议。

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

#define DIM 256

int scanner(char*[]);
int execute(char*[]);

int main()
{
    char* string[DIM]; 

    scanner(string);
    execute(string);

}

/* scan:    read the input in token*/
int scanner(char* string[])
{
    char input[1024];
    char delimit[]=" \t\r\n\v\f"; 
    int i = 0;

    if(fgets(input, sizeof input, stdin)) {
        string[i] = strtok(input, delimit);
        while(string[i]!=NULL){
            i++;
            string[i]=strtok(NULL,delimit);
        }
        return 0;
    }
    return 1;
}
/* execute:    execute the command*/
int execute(char* string[])
{
    int pid;
    printf("%s\n", string[0]);
    switch(pid = fork()){
        case -1:
            return 1;
        case 0:
            execvp(string[0], string);
            return 1;
        default:
            wait((int*)0);
            return 0;
    }
}

【问题讨论】:

    标签: c system-calls string.h


    【解决方案1】:

    scanner中的字符串变量input是一个局部变量,存储类为“auto”。这意味着当该函数返回时,该变量会消失,并且它占用的内存可以重新用于其他事情。这是不幸的,因为strtok 返回指针那个字符串变量。

    【讨论】:

    • 谢谢!我刚刚尝试将输入声明为静态,现在它可以工作了。
    • 您认为这是正确的解决方案还是我应该尝试其他方法?
    • 将其声明为静态有效,但您也可以将字符串变量作为 main 的输入发送,就像对数组所做的那样。
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2016-01-29
    相关资源
    最近更新 更多