用户在C中输入linux命令

时间:2022-08-09 00:24:41
#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.

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

1 个解决方案

#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:

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

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

#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:

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

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