用户在C中输入linux命令

时间:2013-05-13 02:05:45

标签: c linux

#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;
}

我想在这里尝试实现的是我想读取用户输入,这应该是一个linux命令,然后执行命令。似乎我不能用strtok分割我的字符串。我有点失落,谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您对strtok的连续调用是错误的。你需要通过分隔符。此外,您只是写入数组的第一个元素。试试这个:

int n = 0;
while (token != NULL && n < 7)
{
    arg_list[n++] = token;
    token = strtok(NULL, delim);
}