Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int extcommand(char** const param)
- {
- // Split path by colons
- char** paths = strsplit(getenv("PATH"), ':');
- // This holds the full path to the command if it exists
- char* cmdpath = NULL;
- // The length of the command
- int cmdlen = strlen(*(param));
- int cmdfound = 0;
- // For various loops
- int i;
- #ifdef DEBUG
- // In debug mode, print out all the paths in PATH
- printf("~ Path:\n");
- for(i = 0; i < arraylen((void**)paths); i++)
- printf("~\t%s\n", *(paths + i));
- #endif
- // Try to find the requested command in PATH
- for(i = 0; i < arraylen((void**)paths); i++)
- {
- // The length of the final path is the length of the path + a dash +
- // the command length and the nullbyte
- int len = strlen(*(paths + i)) + cmdlen + 2;
- // This will hold the concatenated string
- char* c = malloc(sizeof(char) * len);
- // Concatenate the path with the command
- sprintf(c, "%s/%s", *(paths + i), *(param));
- // Check if the file exists in this path
- if(fileexists(c))
- {
- // Set cmdpath to the path and break out of the loop
- cmdpath = c;
- break;
- }
- else
- {
- // TODO: Figure out why this free crashes
- // Free the temporary variable
- //free(c);
- }
- }
- // Check if the command was found
- if(cmdpath)
- cmdfound = 1;
- else
- {
- cmdfound = 0;
- // Jump to the end of the function
- goto end;
- }
- /*
- * Fork
- */
- #ifdef DEBUG
- printf("~ Found command at path: %s\n", cmdpath);
- return (1);
- #endif
- // Fork the process using safefork
- pid_t pid = safefork();
- // In case the fork couldn't be completed
- if(pid == -1)
- error("Fork failed");
- // Child process
- else if(pid == 0)
- {
- int result = execve(param[0], param, NULL);
- printf("FAIL!!! Returned %d\n", result);
- exit(1);
- }
- // Parent process
- else
- {
- printf("Child process created on pid %d\n", pid);
- }
- /*
- * End of function
- */
- end:
- // Free the array of paths
- arrayfree((void**)paths);
- // Free the string holding the full path
- if(cmdpath) free(cmdpath);
- // Return 0 if the command couldn't be found, otherwise 1
- return cmdfound;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement