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

void getCommand(char* cmd, char** arg_list)
{
pid_t child_pid;

child_pid = fork();

if (child_pid == 0)
{
    execvp (cmd, arg_list);
    fprintf(stderr, "error");
    abort();
}

}

int main(void)
{

printf("Type the command\n");

char *arg_list[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};

char cmd[20];
char delim[2] = " ";
char *token;

scanf("%[^\n]", cmd);

token = strtok(cmd, delim);

while (token != NULL)
{
    arg_list[0] = token;
    token = strtok(NULL, cmd);
}

getCommand (arg_list[0], arg_list);
return 0;
}

What I'm trying to achieve here is I want to read user input, which should be a linux command, and then execute the command. It seems that I can't use strtok to split my string. I'm kinda lost, thanks for the help.

1
  • 1
    paddy got your main problem. You should get in the habit of checking errno. Printing "error" isn't going to tell you much. Also you might want to have the parent wait on the child. Commented May 13, 2013 at 2:17

1 Answer 1

1

Your successive calls to strtok are wrong. You need to pass the delimiters. Also, you are only writing to the first element of your array. Try this:

int n = 0;
while (token != NULL && n < 7)
{
    arg_list[n++] = token;
    token = strtok(NULL, delim);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.