-1

I'm working on a simple shell for my school project and atm I am trying to pass two input paramaters to be used with a command (ex: ls /home/ -l) as I can only pass 1 atm. Meaning whatever goes after "/home/" doesn't get executed. I've tried this to solve it, but it doesn't and I have no idea what to do.

EDIT: sorry this line was only meant to visualise what are these variables: pid = fork() , char* = arg[30] , char = input .

if(pid != 0) {
        waitpid(-1, &stat, 0) ;
    }
    else {
        if(arg[2]!=0) {
            char* doubleArgument = (char *) malloc(1 + strlen(arg[1])+ strlen(arg[2]) ) + 1;
            strcpy(doubleArgument, arg[1]) ;
            strcpy(doubleArgument, " ") ;
            strcpy(doubleArgument, arg[2]) ;
            execvp(input, doubleArgument) ;
        }
        else {
            execvp(input, arg) ;
            printf("Error detected at: %s\n", strerror(errno)) ;
            exit(-1) ;
        }

What should I do? For any advice - thank you :)

1 Answers1

1

execvp(3): execute file - Linux man page

The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

Not tested, try this:

char* arg[30] ;
char *input ;

/* set arg and input properly */

pid = fork() ;
if(pid != 0) {
    waitpid(-1, &stat, 0) ;
}
else {
    if(arg[2]!=0) {
        char** doubleArgument = malloc(sizeof(char*) * 4) ;
        doubleArgument[0] = input ; /* the file name to execute */
        doubleArgument[1] = arg[1] ;
        doubleArgument[2] = arg[2] ;
        doubleArgument[3] = NULL ;
        execvp(input, doubleArgument) ;
    }
    else {
        execvp(input, arg) ;
        printf("Error detected at: %s\n", strerror(errno)) ;
        exit(-1) ;
    }
}

They say you shouldn't cast the result of malloc() in C.
c - Do I cast the result of malloc? - Stack Overflow

Community
  • 1
  • 1
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Previously it would execute command like: "ls bin -al" as "ls bin" and print an error message, but now it's executing it as "ls bin" and then prints "ls:-al: no such file or directory" – user3320248 Nov 22 '15 at 23:59
  • @user3320248 What do you set to `arg` and `input`? – MikeCAT Nov 23 '15 at 00:21
  • @user3320248 With MikeCAT's changes it looks correct to me. Your latest problem is that you did `ls bin -al` but you really wanted to say was `ls -al bin`. In other words, the `execvp` is now correct, but you were giving an option after the first filename and `ls` was interpreting that as a file [which _correctly_ wasn't found]. – Craig Estey Nov 23 '15 at 03:32