So I have to build a program in C that practically takes a command from keyboard , split it into tokens that are stored in an array and use those tokens as input to "execv" (a command in ubuntu) , I chose the command "uname" with the parameter "-a", but I got stuck at the array storing, as it stores only the first letter of the token which was split.
#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: "); //enter the command
fgets(comanda,sizeof(comanda),stdin); // read the command
char *c = strtok(comanda," "); // split it into tokens
while(c!=0)
{
cuvinte[i] = malloc( strlen( c ) + 1 ); // alocate memory for the array
strcpy(cuvinte[i++],c); //copying tokens into array
printf("%s\n",c); // printing them
c=strtok(NULL, " ,.!?");
}
printf("Sunt %d elemente stocate in array! \n\n",i); //no of tokens stored
printf("Primul cuvant este: \n\n\n"+*cuvinte[1]); //should print the first word
/*i got stucked here because of the tokens */
/*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 */
}
//getch();
return 0;
}