Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <string.h>
- #define MAX_INPUT_SIZE 1024
- int main() {
- char input[MAX_INPUT_SIZE];
- while (1) {
- printf("MyShell> ");
- fgets(input, MAX_INPUT_SIZE, stdin);
- // Remove newline character
- input[strlen(input) - 1] = '\0';
- if (strcmp(input, "exit") == 0) {
- printf("Exiting MyShell...\n");
- break;
- }
- pid_t child_pid = fork();
- if (child_pid == -1) {
- perror("fork");
- return 1;
- } else if (child_pid == 0) {
- // Child process
- // Tokenize the input into arguments
- char *args[MAX_INPUT_SIZE / 2];
- int arg_count = 0;
- char *token = strtok(input, " ");
- while (token != NULL) {
- args[arg_count] = token;
- arg_count++;
- token = strtok(NULL, " ");
- }
- args[arg_count] = NULL;
- // Check if the last argument is "&" for running in the background
- int run_in_background = 0;
- if (arg_count > 0 && strcmp(args[arg_count - 1], "&") == 0) {
- run_in_background = 1;
- args[arg_count - 1] = NULL; // Remove the "&" from arguments
- }
- // Execute the command
- if (execvp(args[0], args) == -1) {
- perror("execvp");
- exit(1);
- }
- } else {
- // Parent process
- // If not running in the background, wait for the child to finish
- if (strcmp(input, "") != 0 && input[strlen(input) - 1] != '&') {
- wait(NULL);
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement