iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
Software Development

十年後重讀作業系統恐龍本系列 第 12

ch3圖3.35-簡單殼介面的輪廓

  • 分享至 

  • xImage
  •  

simple-shell.c

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAX_LINE 80 /* 80 chars per line, per command */

int main(void) {
    char *args[MAX_LINE / 2 + 1]; /* command line (of 80) has max of 40 arguments */
    int should_run = 1;
    char input[MAX_LINE];
    pid_t pid;
    int i;

    while (should_run) {
        printf("osh>");
        fflush(stdout);

        // Read the input
        if (fgets(input, MAX_LINE, stdin) == NULL) {
            perror("fgets failed");
            continue;
        }

        // Remove newline character from input
        size_t length = strlen(input);
        if (length > 0 && input[length - 1] == '\n') {
            input[length - 1] = '\0';
        }

        // Parse the input into arguments
        char *token = strtok(input, " ");
        i = 0;
        while (token != NULL) {
            args[i++] = token;
            token = strtok(NULL, " ");
        }
        args[i] = NULL;

        // Check if the user entered "exit"
        if (args[0] != NULL && strcmp(args[0], "exit") == 0) {
            should_run = 0;
            continue;
        }

        // Fork a child process
        pid = fork();
        if (pid < 0) {
            perror("fork failed");
            continue;
        } else if (pid == 0) {
            // Child process
            if (execvp(args[0], args) == -1) {
                perror("execvp failed");
            }
            exit(1);
        } else {
            // Parent process
            int background = 0;
            if (i > 0 && strcmp(args[i - 1], "&") == 0) {
                background = 1;
                args[i - 1] = NULL; // Remove '&' from arguments
            }

            if (!background) {
                wait(NULL); // Wait for the child process to complete
            }
        }
    }

    return 0;
}

參考:greggagne/OSC9e/ch3/simple-shell.c


上一篇
ch4-多執行緒
下一篇
ch4圖4.9-使用Pthreads API 多執行緒的C程式
系列文
十年後重讀作業系統恐龍本30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言