2013-05-13 58 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