I create a shell and am having problems with the execvp system call. I saw some other questions on this topic, but they were vague and did not seem to be completely resolved (whoever asked questions, did not provide a lot of information and did not receive good answers).
Obviously, I have my own command line, and I am reading user input from stdin, like
mysh some/path $ ps -a
and I create an args array as char **, and the array itself works (I think), because when I print the values inside my function, it shows
args[0] = 'ps'
args[1] = '-a'
args[2] = '(null)'
So, I call fork and execvp (cmnd, args) in my process where cmnd is “ps” and args is as above, and perror etc.
I get
'Error: no such file or directory.'
$PATH? - ?
args:
char ** get_args(char * cmnd) {
int index = 0;
char **args = (char **)emalloc(sizeof(char *));
char * copy = (char *) emalloc(sizeof(char)*(strlen(cmnd)));
strncpy(copy,cmnd,strlen(cmnd));
char * tok = strtok(copy," ");
while(tok != NULL) {
args[index] = (char *) emalloc(sizeof(char)*(strlen(tok)+1));
strncpy(args[index],tok,strlen(tok)+1);
index++;
tok = strtok(NULL," ");
args = (char**) erealloc(args,sizeof(char*)*(index+1));
}
args[index] = NULL;
return args;
}
(emalloc erealloc - malloc realloc )
, :
void exec_cmnd(char*cmnd, char**args) {
pid_t pid;
if((pid=fork())==0) {
execvp(cmnd, args);
perror("Error");
free(args);
free(cmnd);
exit(1);
}
else {
int ReturnCode;
while(pid!=wait(&ReturnCode)) {
;
}
}
}
, , execvp , , - , (.. argv == {'ps', NULL})
, . .