problem with fgets and execvp

This is a discussion on problem with fgets and execvp within the C Programming forums, part of the General Programming Boards category; hi, im trying to read input from the user with fgets for example "ls" then use execvp to make the ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    19

    problem with fgets and execvp

    hi, im trying to read input from the user with fgets for example "ls" then use execvp to make the command happen but when i try it nothing happens. what am i missing?

    Code:
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #define MAXSIZE 10
    
    main()
    
    {
       char *inputString;
       inputString = malloc(MAXSIZE);
       char *const parmList[] = 
       {"/bin/ls", NULL};
    
       printf("Please enter a string: ");
       fgets(inputString, MAXSIZE, stdin);
       execvp(inputString, parmList);
       free(inputString);
    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    That depends. Is ... ls /bin/ls ... a valid command? (cause that's what you're sending it)

    Does execvp() return an error? (you probably should be checking that)

    Also, don't forget that the string entry from fgets() includes the carriage return, so you probably need to strip that out before calling the function.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    2,693
    Your problem is probably the newline character at the end of your input string. Remember fgets() puts the end of line character into the destination string. Also main should be defined to return an int, int main(void).

    This works for me:
    Code:
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    // Add this include for the strlen() function.
    #include <string.h>
    
    #define MAXSIZE 10
    
    int main()
    
    {
       char inputString[MAXSIZE];
       char *const parmList[] =   {"/bin/ls", NULL};
    
       printf("Please enter a string: ");
       fgets(inputString, MAXSIZE, stdin);
       inputString[strlen(inputString)-1] = '\0';
       execvp(inputString, parmList);
    }
    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets() Problem
    By kihina in forum C Programming
    Replies: 3
    Last Post: 02-08-2010, 10:03 AM
  2. Problem with fgets !
    By Astra in forum C Programming
    Replies: 6
    Last Post: 11-18-2006, 08:23 PM
  3. fgets problem!
    By chodmama in forum C Programming
    Replies: 4
    Last Post: 02-21-2006, 03:10 AM
  4. fgets problem (i think)
    By GanglyLamb in forum C Programming
    Replies: 3
    Last Post: 03-19-2003, 10:19 AM
  5. fgets problem
    By gambitmj in forum C Programming
    Replies: 5
    Last Post: 02-26-2002, 07:55 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21