简体   繁体   中英

execvp not working with command line argument

I am working on this program to run the shell command given via command line argument using system calls execvp() and fork() . Here arglist is a 2D array which contains the command name and its argument list. I am passing command name as the first argument and the arglist array as the second argument. But it is not working. man page of execvp() says that it will look for the given command by default in the directories defined by PATH variable, that is why I am passing just command name.

#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<string.h>

void executeCommand(char *command,char **arglist){

    int pid;
    int status;

    pid=fork();

    printf("%s %s\n",command,arglist[1]);

    if(pid == -1){
        printf("fork failed\n");
        exit(1);
    }
    else if(pid==0){

        if(execvp(command,arglist) == -1){
            printf("execution of command failed\n");
            exit(1);
        }
        exit(0);
    }
    else {

        while(wait(&status) != pid);

        printf("Parent Exiting\n");
        exit(0);
    }


}


int main(int argc,char **argv){

    char **arglist,*com;
    int i,k=1;

    if(argc>2){
        arglist = (char**)malloc(sizeof(char*)*(argc));
        for(i=0;i<argc-1;i++){
            arglist[i] = (char*)malloc(sizeof(char)*1024);

        }   
        com = (char*)malloc(sizeof(char)*strlen(argv[1]));      

        strcpy(com,argv[1]);
        for(i=1;i<=(argc-1);i++,k++){
            strcpy(arglist[k],argv[i]);

        }
        arglist[k] = NULL ;
        for(i=0;i<argc;i++){
            printf("%s\n",argv[i]);
        }

        executeCommand(argv[1],arglist);



    }

    //printf("%d\n",argc);




    return 0;
}

You are not allocating enough space for the command when you do

com = (char*)malloc(sizeof(char)*strlen(argv[1]));

since it doesn't make space for the terminator, you need to add one to the result of strlen as in

com = (char*)malloc(sizeof(char)*(1+strlen(argv[1])));

Even easier would be to use strdup instead of malloc/strcpy. Then you just need to say

com = strdup(argv[1]);

and

arglist[k] = strdup(argv[i]);

and remove all of the mallocs except the one creating the space for arglist itself.

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