2013-05-13 63 views
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; 
} 

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

+1

稻田得到你的主要问题。你应该养成检查errno的习惯。打印“错误”不会告诉你很多。你也可能想让父母对孩子“等待”。 – Duck 2013-05-13 02:17:23

回答

1

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

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

非常感谢你,我绝对使用strtok错误。 – Sibanak 2013-05-13 02:50:51