TheCoder
TheCoder

Reputation: 1

Passing arguments to execv() system call

I'm trying to build a version of a linux shell wherein, I take in the commands from the user and execute the commands using execv() system call. I'm using strtok_r to tokenize the commands and pass the arguments to execv(). For example, when the user types in the command "ls -l", I first remove the leading/trailing white spaces and then tokenize the command into two tokens 1) ls, 2) -l. I concatenate the first token with a char path[10] in which I've already copied "/bin/" path. So, after concatenation, path becomes "/bin/ls". However, the execv() call fails. But, when I directly pass "/bin/ls" (instead of passing it as a variable) as the argument in execv(), it works. Code is shown below: Please let me know where I've committed the mistake. `

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>

void removeTrailingLeadingSpaces(char* stringInput);
int main () 
{
    printf("dash> ");
    char* input;
    size_t characters;
    size_t bufsize = 32;
    input = (char *)malloc(bufsize*sizeof(char));
    characters = getline(&input,&bufsize,stdin);
    
    removeTrailingLeadingSpaces(input);
    char *args[2];
    char* last;
    char* token; 
    token = strtok_r(input," ",&last);
    printf("%s\n", token);
    removeTrailingLeadingSpaces(token);
    char path[10];
    strcpy(path,"/bin/");
    strcat(path,token);
    args[0] = path;
    printf("%s\n",args[0]);
    args[1] = strtok_r(NULL," ",&last);
    args[2] = NULL;
    
    int i = access(args[0],X_OK);
    printf("result is %d",i); 
    
    int j= execv(args[0],args);
    printf("result2 is %d",j); 
    return 0;

}

void removeTrailingLeadingSpaces(char* input)
{
    while(isspace((unsigned char)*input)) 
     input++;
    int i=strlen(input)-1;
    while(i>0)
    {
        if(input[i] == ' '|| input[i] == '\n'|| input[i] =='\t')
        i--;
        else
        break;
    }
    input[i+1] = '\0';
}

`

Upvotes: 0

Views: 205

Answers (0)

Related Questions