1

したがって、キーボードから実際にコマンドを取得し、配列に格納されているトークンに分割し、それらのトークンを「execv」(ubuntuのコマンド)への入力として使用するプログラムをCで構築する必要があります。コマンド「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

最初に追加

 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 に答える