<stdlib.h>에 있는 system() 을 사용해서 shell scipt를 실행가능하다!

#include <stdlib.h>

int main()
{
    system("echo HI");
    system("ls");

    return 0;
}

실행결과

 

예시: 쉘 제작해보기

작성해본 코드

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

#define MAX_HISTORY_SIZE 100
#define MAX_COMMAND_LEN 100

// Define command
typedef struct {
    int id;
    char command[MAX_COMMAND_LEN];
} Log;

int cnt = 0;
Log command_log[MAX_HISTORY_SIZE];

void RecordCommand(char* input)
{
    cnt++;
    strcpy(command_log[cnt].command, input);
    command_log[cnt].id = cnt;
}

int main()
{
    while (1)
    {
        char input[100];
        // input command
        printf("SSAFY>_ ");
        fgets(input, sizeof(input), stdin);

        // remove "\n"
        input[strcspn(input, "\n")] = 0;

        // input !_number
        if (input[0] == '!' && atoi(input + 1) >= 0 && atoi(input + 1) < cnt)
        {
            int command_no = atoi(input + 1);
            // printf("%s\n", command_log[command_no].command);
            strcpy(input, command_log[command_no].command);
        }

        // commands
        if (strcmp(input, "date") == 0)
        {
            system("date");
            RecordCommand(input);
            continue;
        }
        if (strcmp(input, "uptime") == 0)
        {
            system("uptime");
            RecordCommand(input);
            continue;
        }
        if (strcmp(input, "ls") == 0)
        {
            system("ls -al");
            RecordCommand(input);
            continue;
        }
        if (strcmp(input, "log") == 0)
        {
            system("dmesg");
            RecordCommand(input);
            continue;
        }
        if (strcmp(input, "exit") == 0)
        {
            break;
        }
        if (strcmp(input, "hclear") == 0)
        {
            cnt = 0;
            continue;
        }

        if (strcmp(input, "history") == 0)
        {
            for (int i = 1; i <= cnt; i++)
            {
                printf("%d %s\n", command_log[i].id, command_log[i].command);
            }
            RecordCommand(input);
            continue;
        }
        else
        {
            printf("ERROR\n");
        }
    }

    return 0;
}

+ Recent posts