기계는 거짓말하지 않는다

C 디렉터리 소유권 변경, chown 함수 본문

C

C 디렉터리 소유권 변경, chown 함수

KillinTime 2024. 7. 18. 19:03

디렉터리를 생성한 후, 생성된 디렉터리의 소유권을 변경하고 싶다면 chown 함수를 사용하여

디렉터리의 소유권을 변경할 수 있다. 아래는 예제 코드이며 UID, GID를 사용한다.

unistd.h, sys/types.h 헤더 파일을 포함해야 한다.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>

// UID, GID를 사용하여 소유권을 변경하는 함수
int change_directory_ownership(const char* path, uid_t owner, gid_t group) {
    if (chown(path, owner, group) == -1) {
        perror("chown error");
        return -1;
    }
    return 0;
}

int create_directory_with_permissions(const char* data_dir_path) {
    if (access(data_dir_path, F_OK) == -1) {  // 디렉토리가 존재하지 않으면
        if (mkdir(data_dir_path, 0775) == -1) {  // 디렉토리 생성
            perror("make directory error");
            return -1;
        }
        
        // 소유권 변경 (UID 1000과 GID 1000을 사용. 필요에 따라 변경)
        if (change_directory_ownership(data_dir_path, 1000, 1000) == -1) {
            return -1;
        }
    }
    return 0;
}

int main() {
    const char* data_dir_path = "/path/to/directory";
    
    if (create_directory_with_permissions(data_dir_path) == -1) {
        return -1;
    }
    
    return 0;
}
Comments