CS/UNIX

[Directory Management] - chdir / fchdir 함수

sliver__ 2022. 10. 21. 23:37
728x90
  • 현재 디렉토리를 프로그램에서 변경하기 위해서, chdir 함수를 사용한다.
  • prototype은 아래와 같다.
#include <unistd.h>

int chdir(const char *path);
  • path에 옮기고 싶은 경로의 디렉토리를 적는다.
  • 존재하는 디렉토리를 파라미터로 넘긴다.
  • 성공하면 0을 리턴
  • 실패하면 -1을 리턴하고 errno에 이유를 적는다.

 

if ( chdir("/home/games") == -1 ) {
    fprintf(stderr,"%s: chdir(2)\n",strerror(errno));
    exit(13);
}
  • /home/games 디렉토리로 변경하는 예제이다.
  • 실패하면 status code 13으로 종료한다.

 

[Working Directory 저장]

  • 현재 있는 디렉토리 위치를 저장하고 다른 디렉토리로 이동한 후 원래 디렉토리로 돌아올 경우, 디렉토리 이름이 변경되어 있으면 돌아올 수 없다.
  • 이럴 경우에 fchdir을 사용한다.
  • 프로토타입은 아래와 같다.
#include <unistd.h>

int fchdir(int fd);
  • file descriptor로 디렉토리를 찾는다.
  • 아래는 fchdir 예제 코드이다.
int fd;

fd = open("/etc",O_RDONLY);    /* Open the directory */
if ( fd == -1 )
    /* Report open error */

if ( fchdir(fd) == -1 )        /* Change to directory ref'd by fd */
    /* Report error */
else
    /* Current directory is now /etc */

 

[fchidr의 한계]

  • 디렉토리 권한이 실행만 있을 경우 open으로 열 수 없다는 점이다.
$ ls -dl /tmp/x_only
d--x--x--x  2 me   mygrp  512 Apr 29 14:38 /tmp/x_only
$
$ cd /tmp/x_only
$
  • 위 경우 shell에서 cd로 디렉토리에 접근할 수 있지만 read 권한이 없으므로 open 함수로 열 수 없다.
728x90