2. Write a program to implement the shell. It should display the command prompt “myshell$”. Tokenize the command line and execute the given command by creating the child process. Additionally it should interpret the following ‘list’ commands as 
myshell$ list f dirname :- To print names of all the files in current directory.
myshell$ list n dirname :- To print the number of all entries in the current directory.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>

// Function to execute the 'list' commands
void handle_list_command(char **args) {
    if (args[1] == NULL || args[2] == NULL) {
        printf("Usage: list [f|n] dirname\n");
        return;
    }
    
    char *option = args[1];
    char *dirname = args[2];
    DIR *dir;
    struct dirent *entry;
    int count = 0;

    dir = opendir(dirname);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    if (strcmp(option, "f") == 0) {
        // Print names of all files in the directory
        while ((entry = readdir(dir)) != NULL) {
            printf("%s\n", entry->d_name);
        }
    } else if (strcmp(option, "n") == 0) {
        // Print the number of all entries in the directory
        while ((entry = readdir(dir)) != NULL) {
            count++;
        }
        printf("Number of entries: %d\n", count);
    } else {
        printf("Invalid option. Use 'f' to list files or 'n' to count entries.\n");
    }

    closedir(dir);
}

// Function to parse and execute commands
void execute_command(char *command) {
    char *args[4];
    char *token;
    int i = 0;

    token = strtok(command, " \t\n");
    while (token != NULL && i < 4) {
        args[i++] = token;
        token = strtok(NULL, " \t\n");
    }
    args[i] = NULL;

    if (args[0] == NULL) {
        // Empty command
        return;
    } else if (strcmp(args[0], "list") == 0) {
        handle_list_command(args);
    } else {
        // Fork and execute external commands
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork");
        } else if (pid == 0) {
            // Child process
            execvp(args[0], args);
            perror("execvp");
            exit(EXIT_FAILURE);
        } else {
            // Parent process
            wait(NULL);
        }
    }
}

int main() {
    char command[1024];

    while (1) {
        // Display command prompt
        printf("myshell$ ");
        fflush(stdout);

        // Read command from stdin
        if (fgets(command, sizeof(command), stdin) == NULL) {
            perror("fgets");
            exit(EXIT_FAILURE);
        }

        // Exit if command is "exit"
        if (strncmp(command, "exit", 4) == 0) {
            break;
        }

        // Execute the command
        execute_command(command);
    }

    return 0;
}