Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #define MAX_ARGS 10
- int main() {
- char command[100];
- char *args[MAX_ARGS];
- pid_t pid;
- printf("Enter command: ");
- fgets(command, sizeof(command), stdin);
- // Remove trailing newline from the input
- command[strcspn(command, "\n")] = 0;
- // Tokenize the command and arguments
- char *token = strtok(command, " ");
- int argc = 0;
- while (token != NULL && argc < MAX_ARGS - 1) {
- args[argc++] = token;
- token = strtok(NULL, " ");
- }
- args[argc] = NULL; // Null-terminate the argument list
- // Check if the command contains a path separator
- if (strchr(args[0], '/') != NULL) {
- // Command contains an absolute path
- pid = fork();
- if (pid == -1) {
- perror("fork");
- exit(EXIT_FAILURE);
- } else if (pid == 0) {
- // Child process
- execv(args[0], args);
- perror("execv");
- exit(EXIT_FAILURE);
- } else {
- // Parent process
- wait(NULL); // Wait for child to finish
- }
- } else {
- // Command does not contain an absolute path
- // Search for the command in PATH
- char *path = getenv("PATH");
- if (path == NULL) {
- fprintf(stderr, "PATH environment variable not found.\n");
- exit(EXIT_FAILURE);
- }
- char *path_copy = strdup(path);
- token = strtok(path_copy, ":");
- while (token != NULL) {
- // Construct the full path
- char full_path[100];
- snprintf(full_path, sizeof(full_path), "%s/%s", token, args[0]);
- // Check if the file exists
- if (access(full_path, X_OK) == 0) {
- pid = fork();
- if (pid == -1) {
- perror("fork");
- exit(EXIT_FAILURE);
- } else if (pid == 0) {
- // Child process
- execv(full_path, args);
- perror("execv");
- exit(EXIT_FAILURE);
- } else {
- // Parent process
- wait(NULL); // Wait for child to finish
- break; // Exit loop since command was found and executed
- }
- }
- token = strtok(NULL, ":");
- }
- free(path_copy);
- if (token == NULL) {
- // Command not found in PATH
- fprintf(stderr, "Command not found.\n");
- exit(EXIT_FAILURE);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement