Xri Xri -4 years ago 146
Bash Question

command line intepreter in c

I want to create a command line interpreter with more than one comamnd per line.
I will enter from the keybord commands like:

pwd ; ls ; cat file ; ls -l


I wrote this, can someone help me with warnings?

Warning are:

ex.c: In function ‘Execute’:

ex.c:33:18: warning: passing argument 1 of ‘execvp’ from incompatible pointer type [-Wincompatible-pointer-types]
if(execvp(cmd, pin) == -1) {

In file included from ex.c:3:0:

/usr/include/unistd.h:581:12: note: expected ‘const char *’ but argument is of type ‘char **’
extern int execvp (const char *__file, char *const __argv[])


ex.c: In function ‘main’:

ex.c:105:17: warning: passing argument 1 of ‘Execute’ from incompatible pointer type [-Wincompatible-pointer-types]

Execute(pin[0],pin);


ex.c:21:6: note: expected ‘char **’ but argument is of type ‘char *’
void Execute(char* cmd[],char* pin[]) {
^~~~~~~


Sorry for bad english.

#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_SIZE 512

//Clean function
void Clean(char* cmd[],char* pin[]) { //Clean Array

int a;
for(a=0; a < 40; a++){
cmd[a] = NULL;
pin[a] = NULL;
}
}

//execute commands

void Execute(char* cmd[],char* pin[]) {

pid_t pid;
pid = fork();

switch(pid) {
case -1:
printf("DEBUG:Fork Failure\n");
exit(-1);
case 0:
execvp(*cmd, pin);

if(execvp(cmd, pin) == -1) {
printf("Command Not Found\n");
exit(0);
}

default:
wait(NULL);
printf("DEBUG:Child Finished\n");
}
}

int main() {
char* cnd;
char* cmd[40];
char* pin[40];
char* array;
int how_much;

char *input = malloc (MAX_SIZE);

if (input == NULL) {
printf ("No memory\n");
return 1;
}

Clean(cmd,pin);

printf("shell> ");

fgets (input, MAX_SIZE, stdin);

if ((strlen(input)>0) && (input[strlen (input) - 1] == '\n')) {
input[strlen (input) - 1] = '\0';
}

printf("INPUT: %s\n", input);

//searching for ";"

cnd = strtok(input, ";");

int i = 0;

while(cnd != NULL) {
cmd[i] = cnd;
i++;
cnd = strtok(NULL, ";");
}

cmd[i] = NULL;
how_much = i;

// searching for " "

for(int j=0; j < how_much; j++) {
array = strtok(input, " ");

int k=0;

while(array != NULL) {
pin[k] = array;
k++;
array = strtok(NULL, " ");
}

pin[k] = NULL;

Execute(pin[0],pin);
}

free (input);

return 1;
}

Answer Source

In the Execute function:

...
case  0:
  execvp(*cmd, pin);

  if (execvp(cmd, pin) == -1) {
  ...

You have first execvp(*cmd, pin) and then execvp(cmd, pin). Does this should suggest you what's wrong.

And here:

Execute(pin[0],pin);

In the first argument Execute expects an array of char*, but you provide a char*.

There are probably more problems.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download