简体   繁体   中英

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);
}

when I run this code with ls command this is the result. I don't know what is the problem with this code. When I run this code to execute another .c file it execute perfectly but when I try to use ls or ps command it does not let me use it and throws the error.

I have one more question why this goto does not working in this program .

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

so here is my mistake and can you give me some advise on how to use exec command and its different types.

If they don't provide an argument, set that argument in args to 0 . Then ls won't receive an empty string as its first argument, it won't get any arguments at all.

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

You also need to check for this in the loop that prints all the arguments.

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]);
    }

I was passing the blank space as the second argument. so it was showing me the error. Above code is the solution of my problem..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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