I am building a simple shell program that does a few things. one requirement my professor is giving us is that once a program is compiled through the shell (just using cc) then the result, a.out, can be searched for if it is not in the directory you are currently in. I cannot find anything about doing this.
my code works fine to run it using ./a.out, I can also go into a subdirectory by doing ./test/a.out like normal. But I have no idea how I would go about having the shell search for the compiled program and run it from where it is. Any help would be greatly appreciated. parts of the code are below.
Here is the commandhandler, the final else is what sends the code to be run
int commandHandler(char * args[]){
int i = 0;
int j = 0;
int fileDesc;
int standardOut;
int aux;
int background = 0;
char *args_aux[256];
//array for the arguments
while ( args[j] != NULL){
args_aux[j] = args[j];
j++;
}
// 'quit' command quits the shell
if(strcmp(args[0], "quit") == 0) {
exit(0);
}
// 'pwd' command prints the current directory
else if (strcmp(args[0], "pwd") == 0){
printf("%s\n", getcwd(currentDirectory, 1024));
}
// 'cd' command to change directory
else if (strcmp(args[0], "cd") == 0) {
changeDirectory(args);
}
// 'delDir' command to delete a directory (works on directories that are not empty)
else if (strcmp(args[0], "delDir") == 0) {
char* foldername = args[1];
deleteDir(foldername);
}
//this is to run any specific program, like the i_did_it program!
else {
while (args[i] != NULL && background == 0){
i++;
}
args_aux[i] = NULL;
launchProg(args_aux, background);
}
return 1;
}
Then below is the launchProg function
void launchProg(char **args, int background) {
int err = -1;
if((pid = fork()) == -1){
printf("Child process could not be created\n");
return;
}
//child process
if(pid == 0){
//child process ignores SIGINT signals
signal(SIGINT, SIG_IGN);
//set parent var to environment variable
setenv("parent", getcwd(currentDirectory, 1024), 1);
// If a command does not exist
if (execvp(args[0],args) == err){
printf("Command not found");
kill(getpid(),SIGTERM);
}
}
//parent process
if (background == 0) {
waitpid(pid,NULL,0);
}
else {
printf("Process created with PID: %d\n",pid);
}
}