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 |