1

Here is the general problem: The program must fork() and wait() for the child to finish. The child will exec() another program whose name is INPUT by the user.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    int status;
    char input[BUFSIZ];
    printf(">");
    scanf("%s",input);
    char *args[] = {"./lab1"};
    pid_t pid = fork();
    if(pid==0){
    execvp(args[0],args);
    }else if(pid<0){
        perror("Fork fail");
    }else{
        wait(&status);
        printf("My Child Information is: %d\n", pid);
    }
    return 0;
}

My problem is getting the user to input a program name to run (at the ">" prompt) and getting that input into execvp (or another exec() function if anyone has any ideas)

dell44223
  • 13
  • 1
  • 5

1 Answers1

0

I'm going to hold off lambasting you for using scanf("%s") for now, though you should be aware it's really not robust code.

Your basic task here is going to be taking a character array entered by the user and somehow turning that into an array of character pointers suitable for passing to execvp.

You can use strtok to tokenise the input string into tokens separated by spaces, and malloc/realloc to ensure you have enough elements in an array to store the strings.

Alternatively, since you already have a potential buffer overflow issue, it may be good enough to just use a fixed size array.


For example, the following program shows one way of doing this, it uses a fixed string echo my hovercraft is full of eels and tokenises it to be suitable for execution:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static char *myStrDup (char *str) {
    char *other = malloc (strlen (str) + 1);
    if (other != NULL)
        strcpy (other, str);
    return other;
}

int main (void) {
    char inBuf[] = "echo my hovercraft is full of eels";
    char *argv[100];
    int argc = 0;

    char *str = strtok (inBuf, " ");
    while (str != NULL) {
        argv[argc++] = myStrDup (str);
        str = strtok (NULL, " ");
    }
    argv[argc] = NULL;

    for (int i = 0; i < argc; i++)
        printf ("Arg #%d = '%s'\n", i, argv[i]);
    putchar ('\n');

    execvp (argv[0], argv);

    return 0;
}

Then it outputs the tokenised arguments and executes it:

Arg #0 = 'echo'
Arg #1 = 'my'
Arg #2 = 'hovercraft'
Arg #3 = 'is'
Arg #4 = 'full'
Arg #5 = 'of'
Arg #6 = 'eels'

my hovercraft is full of eels
Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • This is for class, learning about fork and exec, thanks for your response, I am trying to keep this as simple as possible. – dell44223 Oct 16 '15 at 01:40