繁体   English   中英

ls 命令在用 C(shell 脚本)编写的程序中不起作用

[英]ls command does not work in the Program written in C(shell script)

void main() {
    char *args[MAX_LINE];
    char arg1[MAX_LINE/2] = "\0";
    char arg2[MAX_LINE/2] = "\0";
    printf("ubos>");
    fflush(stdout);
    fgets(arg1, sizeof(arg1), stdin);
    arg1[strlen(arg1) - 1] = '\0';
    fgets(arg2, sizeof(arg2), stdin);
    arg2[strlen(arg2) - 1] = '\0';

  abc:  
    printf("You typed: %s %s\n", arg1, arg2);
    fflush(stdin);
    args[0] = arg1;
    args[1] = arg2;
    args[2] = '\0'; 

    int i = 0;
    for (i = 0; i < MAX; i++) {
        printf("Vlue of arg[%d] =%s\n", i, args[i]);
    }

    if (strcmp(args[0], "ls") == 0) {
        execvp(args[0], args);
        goto abc;
    } else
    if (strcmp(args[0], "ps") == 0) {

    }

    printf("Something is not correct...\n");
    exit(0);
}

当我使用ls命令运行此代码时,结果就是这样。 我不知道这段代码有什么问题。 当我运行此代码以执行另一个.c文件时,它会完美执行,但是当我尝试使用lsps命令时,它不允许我使用它并引发错误。

我还有一个问题,为什么这个goto在这个程序中不起作用。

ubos>ls

You typed: ls 
Vlue of arg[0] =ls
Vlue of arg[1] =
Vlue of arg[2] =(null)
ls: cannot access : No such file or directory

所以这是我的错误,你能给我一些关于如何使用exec命令及其不同类型的建议吗?

如果他们不提供参数,请将args该参数设置为0 然后ls不会接收空字符串作为它的第一个参数,它根本不会得到任何参数。

args[0] = arg1;
if (strlen(arg2) == 0) {
    args[1] = 0;
} else {
    args[1] = arg2;
    args[2] = 0;
}

您还需要在打印所有参数的循环中检查这一点。

for(i=0;i<MAX && arg[i];i++)
{
    printf("Value of arg[%d] =%s\n",i, args[i]);
}
if (strlen(arg2) == '\0')
    {
         args[0] = arg1;
         args[1] = '\0';
    } 
    else 
    {
        args[0] = arg1;
            args[1] = arg2;
            args[2] = 0;
    }
for(i=0;i<MAX && args[i];i++)
    {
            printf("Vlue of args[%d] =%s\n",i, args[i]);
    }

我将空格作为第二个参数传递。 所以它向我展示了错误。 上面的代码是我的问题的解决方案..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM