#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    418
    Rep Power
    20

    Execvp fails - (bad address)


    Hi,
    I have a problem that I have been struggling with for hours now.

    I have a function which receives a string as an argument.
    This string should be in the format: <programname> <param1> <param2> <etc>

    The function extracts the program name and stores it in the programName array.
    It also extracts the parameters and stores them in the parameters array.

    It then forks and lets the child call execvp( programName, parameters ) but then the following error occurs: "Cannot execute the requested program.: Bad address".

    c Code:
    /*
    	This function tries to execute the requested program.
    	It takes the requested program + arguments as a parameter.
    	It returns the ID of the child process that is executing the program. 
    */
    pid_t handleRequest( char* request ){
    	int i=1;
    	char programName[MAX_PROGRAM_NAME_LENGTH];
    	char* parameters[MAX_NUMBER_OF_PARAMETERS];
    	char* token;
     
    	// extract program name from user input.
    	token = strtok( request, " " );
    	strncpy( programName, token, MAX_PROGRAM_NAME_LENGTH );
     
    	// extract parameters from user input and store in array.	
    	parameters[0] = programName;
    	while( (token = strtok( NULL, " " )) && i < MAX_NUMBER_OF_PARAMETERS ){
    		parameters[i] = token;
    		i++;
    	}
     
    	pid_t pid = fork();
    	if( pid ==  0 ){ 
    		if ( execvp( programName, parameters ) == -1 ){
    			perror("Cannot execute the requested program.");
    			exit(1);
    		}
    	} else if( pid == -1 ){
    		perror("Failed to fork!\n");
    		exit(1);
    	}
     
    	return pid;
    }

    Can anyone see what is causing my problem? Any comments on the way I am coding this are welcome too.

    Thanks in advance!
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,403
    Rep Power
    1871
    > parameters[i] = token;
    You need to mark the end of the list with
    parameters[i] = NULL;

    You might need 1 less limit in your loop, to ensure you have space for this NULL.

    Comments on this post

    • Stefan1 agrees
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    418
    Rep Power
    20
    Thanks, that fixed the problem. It's working fine now.

IMN logo majestic logo threadwatch logo seochat tools logo