Hi all,
I'm helping my girl out with her hw, (/me not knowing C at all, but someone has to help, right?)
I am supposed to read user input, and then try to execute a given command plus the arguments in every given $PATH.
I managed it all, but I get puzzled by the execv function, which I am supposed to be using, it doesn't produce any stdio, and I can't seem to find a way to make it work
a basic command
execv ("/bin/touch", "/tmp/test123", NULL);
doesn't do anything, neither do I see an exit code.
How do I use it?
Here's what I've got so far:
void get_path_exec(char cmd[50])
{
char command[50] = {0} ; //full command with path included
char *tempcmd = NULL;
char *result = NULL; //path iterator
char *com[] = {0}; //command with args, no path
char *arg = NULL; //list of arguments, path and command excluded
char delims[] = ":"; //path iteration delimiter
char delims1[] = " "; //
char * path; //variable to hold the full path delimited by ':'
int pid, status; //process flow control
int argcount = 0; //argumetn counter, where 0 is the command
tempcmd=cmd; //assign to temp variable, so strtok doesn't ruin cmd
path=getenv("PATH");
if (path != NULL)
printf("Path is %s \n", path);
else exit(1);
arg = strtok( tempcmd, delims1 );
com[0] = arg; //place the command into com[0]
while( arg )
{
argcount++;
arg = strtok(NULL,delims1);
com[argcount] = arg;
printf("arg is %s \n", arg);
}
argcount++;
com[argcount]=NULL; //last value in args should be NULL, right?
result = strtok( path, delims );
while( result )
{
strcpy(command, "");
strcat(command, result);
strcat(command, "/");
strcat(command,cmd);
strcat(command,"\0"); //gather all parts of full path'd command - path, "/" and cmdname
// printf("full command: %s \n\n", command);
if (( pid = fork()) == 0 ) //create a new process
{
execv(command, com);
//below is a point I don't get
printf("Something happened here, but what? %s \n Status is %d \n\n", result, status);
exit(1);
}
else
{
wait(&status);
printf("Something else happened here %s \n Status after wait is %d", command, status);
if (status != 0)
printf("And something happened again? \n");
}
result = strtok( NULL, delims );
}
}
The entire pid-fork-&status structure is just too vague for me, can anyone explain what happens on every step of the way?
Using execl, by the way, worked for me, but I have to use execv.
Thanks