1

因此,我必须在 C 中构建一个程序,该程序实际上从键盘获取命令,将其拆分为存储在数组中的标记,并将这些标记用作“execv”(ubuntu 中的命令)的输入,我选择了命令“uname ” 带有参数“-a”,但由于某种原因,它一直说“Comanda necunoscuta!” (未知命令!)这是我的代码:

#include <stdio.h>
#include<stdlib.h>
#include <string.h>   /*strtok strcpy*/
#include<malloc.h>   /*malloc*/
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* waitpid */
#include <unistd.h>    /* _exit, fork */

int main()
{
    int i=0;
    char *cuvinte[256]; //words
    char comanda[256];  //command

    printf("Introduceti comanda: "); // command input
    fgets(comanda,sizeof(comanda),stdin); // read command
    char *c = strtok(comanda," "); // break command into tokens

    while(c!=0)
    {
        cuvinte[i] = malloc( strlen( c ) + 1 ); //alocate memory
        strcpy(cuvinte[i++],c); // copy them
        printf("%s\n",c);       // print them
        c=strtok(NULL, " ,.!?");
        }
    printf("Sunt %d elemente stocate in array! \n\n",i); // no of elements stored
    printf("Primul cuvant este: %s \n\n",cuvinte[0]); // shows the first token
    if((cuvinte[0]=='uname')&&(cuvinte[1]=='-a')){    // here lays the problem i guess
      /*face un proces copil*/
      pid_t pid=fork();
        if (pid==0) { /* procesul copil*/
        static char *argv[]={"/bin/uname","-a",NULL};
        execv(argv[0],argv);
        exit(127); /*in caz ca execv da fail*/
        }
        else { /* pid!=0; proces parinte */
        waitpid(pid,0,0); /* asteapta dupa copil */
        }
    }
    else printf("Comanda necunoscuta !\n"); // problem
    //getch();
    return 0;
}
4

2 回答 2

2

首先,我没有足够的声誉来发表评论,对此感到抱歉。

我不确定您是否可以将两个字符串与 C 中的 '==' 运算符进行比较。尝试使用 strcmp 函数。

于 2014-11-05T13:09:55.733 回答
2

首先添加

 cuvinte[1][strlen(cuvinte[1])-1]='\0';

在while循环之后和"printf("Sunt %d elemente stocate in array!\n\n",i);"之前

第二件事

采用

 if((strcmp(cuvinte[0],"uname")==0) && (strcmp(cuvinte[1],"-a")==0))

而不是“==”

程序将工作!

于 2014-11-05T13:12:00.777 回答