因此,我必须在 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;
}