Thread: problem with fgets and execvp

  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
    4,632
    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, 11:03 AM
  2. Problem with fgets !
    By Astra in forum C Programming
    Replies: 6
    Last Post: 11-18-2006, 09:23 PM
  3. fgets problem!
    By chodmama in forum C Programming
    Replies: 4
    Last Post: 02-21-2006, 04:10 AM
  4. fgets problem (i think)
    By GanglyLamb in forum C Programming
    Replies: 3
    Last Post: 03-19-2003, 11:19 AM
  5. fgets problem
    By gambitmj in forum C Programming
    Replies: 5
    Last Post: 02-26-2002, 08:55 AM