[쉘 구현하기] execv() 사용을 위한 문자열 배열 만들기

2023. 8. 11. 16:02·Linux/쉘, 쉘 명령어 구현하기

exec()류 함수를 사용할 때 실행 인자를 전달하기 위해 공백을 포함한 문자열을 공백(탭)을 기준으로 분리하는 함수를 구현하려고 한다.

이것을 만드는 목적은 명령어를 호출할 때 옵션을 사용할 수 있도록 하기 위해서 이다.

 

만약 문자열의 내용이 다음과 같다면,

"hello castle asm 1234 bye" 이 문자열을 

argv[6] = { "hello", "castle", "asm", "1234", "bye", (char *)NULL } 로 만드는 것이 목적이다.

exec()류 함수의 인자를 전달할 때는 꼭 마지막이 NULL이어야 하기 때문에 NULL도 추가해줘야 한다.

 

문자열을 분리할 때는 strtok() 함수를 사용했다.

문자열 배열의 마지막 값이 NULL인지 확인하는 것까지 코드로 구현했다.

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

char **divideString(char *str, int *cnt, char *del) {
    *cnt = 0;
    char *tempList[100] = {(char *)NULL, };
    char **retList = (char **)malloc(sizeof(char *) * (*cnt + 1));
    char *token = NULL;

    token = strtok(str, del);
    if (token == NULL) return NULL;
    while (token != NULL) {
        tempList[(*cnt)++] = token;
        token = strtok(NULL, del);
    }

    for (int i = 0; i < *cnt; i++) {
         retList[i] = tempList[i];
    }
    return retList;
}

int main( int argc, char **argv) {
    char input[4096];
    char **argList = { NULL, };
    int cnt;
    fgets(input, 4096, stdin);
    input[strlen(input) - 1] = '\0';
    argList = divideString(input, &cnt, " \t");

    for (int i = 0; i < cnt + 1; i++) {
        if (argList[i] == NULL) {
            printf("NULL\n");
            continue;
        }
        printf("%s\n", argList[i]);
    }
}

/*
실행 결과 :
hello castle asm 1234 bye
hello
castle
asm
1234
bye
NULL
*/

잘 동작하는 것을 확인했으니 이 코드를 my_header.h 파일에 추가해주자.

 

코드는 아래 이미지를 클릭해 깃허브에서도 확인할 수 있다.

깃허브 이미지 링크

저작자표시 (새창열림)

'Linux > 쉘, 쉘 명령어 구현하기' 카테고리의 다른 글

[쉘 구현하기] ls 명령어 -a 옵션 추가  (0) 2023.08.11
[쉘 구현하기] fork(), exec()류 함수 호출 시 실행인자 주기  (0) 2023.08.11
[쉘 구현하기] ls 명령어 터미널 크기에 최적화  (0) 2023.08.09
[쉘 구현하기] ls 명령어 구현  (0) 2023.08.09
[쉘 구현하기] pwd 명령어 구현  (0) 2023.08.08
'Linux/쉘, 쉘 명령어 구현하기' 카테고리의 다른 글
  • [쉘 구현하기] ls 명령어 -a 옵션 추가
  • [쉘 구현하기] fork(), exec()류 함수 호출 시 실행인자 주기
  • [쉘 구현하기] ls 명령어 터미널 크기에 최적화
  • [쉘 구현하기] ls 명령어 구현
Study with Me!
Study with Me!
Study with Me!
  • Study with Me!
    Seongmo
    Study with Me!
  • 전체
    오늘
    어제
    • Computer (136) N
      • Computer Science (61)
        • Data Structure (51)
        • Algorithm (6)
        • 선형대수 with C++ (4)
      • Arm Architecture (1)
        • Register (0)
        • Assembly Instruction (1)
      • Linux (32) N
        • Linux Kernel (4)
        • 라이브러리 함수 구현하기 (0)
        • 쉘, 쉘 명령어 구현하기 (15)
        • Ubuntu (13) N
      • Cloud Infrastructure (8)
        • Kubernetes (7)
        • OpenStack Magnum (1)
      • AWS (3)
      • Baekjoon (18)
      • Tools (6)
        • Git & Github (5)
        • Vim (1)
      • 개발 환경 (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    STL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Study with Me!
[쉘 구현하기] execv() 사용을 위한 문자열 배열 만들기
상단으로

티스토리툴바