Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

.NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항

리눅스는 실행 파일이 프로그램 동작과 상관없이 잠기지 않기 때문에 언제든 삭제가 가능합니다. (사실 실행 파일뿐만 아니라 로그 파일같은 것도 프로그램에서 열어 사용하는 중간에도 외부에서 삭제할 수 있습니다.)

물론, "파일"뿐만 아니라 "디렉터리"까지 삭제할 수 있습니다. 이럴 경우, 닷넷에서 Environment.CurrentDirectory를 접근하면 FileNotFoundException 예외가 발생하는데, 재현을 위해 다음과 같이 간단한 코드로 테스트할 수 있습니다.

using System;
using System.Diagnostics;
using System.IO;

namespace temp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Environment.CurrentDirectory);

            // delete the directory manually, then press enter key.
            Console.ReadLine();
            Console.WriteLine(Environment.CurrentDirectory);
        }
    }
}

위의 프로그램을 실행하면 다음과 같이 CurrentDirectory를 출력 후 입력을 대기하는데,

$ dotnet ./bin/Debug/netcoreapp2.0/temp.dll
/home/testuser/temp/bin/Debug/netcoreapp2.0

이때 다른 ssh shell을 하나 열어 "./bin/Debug/netcoreapp2.0" 디렉터리를 삭제한 다음,

$ rm -r ./bin/Debug/netcoreapp2.0/

프로그램에서 Console.ReadLine을 넘어가도록 엔터키를 치면 이후의 Environment.CurrentDirectory 속성 접근 시 다음과 같은 예외가 발생합니다.

System.IO.FileNotFoundException: Unable to find the specified file.
    at Interop.Sys.GetCwdHelper(Byte* ptr, Int32 bufferSize)
    at Interop.Sys.GetCwd()
    at System.Environment.get_CurrentDirectory()
    at agent.installer.Program.Main(String[] args)

여기서 재미있는 것은, 설령 사용자가 다시 "/home/testuser/temp/bin/Debug/netcoreapp2.0" 디렉터리를 재생성했어도,

$ rm -r ./bin/Debug/netcoreapp2.0/
$ mkdir ./bin/Debug/netcoreapp2.0

여전히 Environment.CurrentDirectory 속성 접근은 오류가 발생한다는 점입니다.




문제는, Environment.CurrentDirectory 속성이 의외의 작업에서 사용된다는 점입니다. 예를 들어, 다음과 같이 Process.Start로 자식 프로세스를 실행하려는 경우,

static bool Run()
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "chmod";

    Process child = Process.Start(psi);
    child.WaitForExit();
    return true;
}

일반적인 상황에서는 위의 프로그램은 잘 실행이 됩니다. 하지만, 저 프로그램을 소유한 디렉터리가 삭제된 경우에는 위의 Run 메서드에서는 다음과 같은 오류가 발생합니다.

System.IO.FileNotFoundException: Unable to find the specified file.
   at Interop.Sys.GetCwdHelper(Byte* ptr, Int32 bufferSize)
   at Interop.Sys.GetCwd()
   at System.Environment.get_CurrentDirectory()
   at System.IO.Directory.GetCurrentDirectory()
   at System.Diagnostics.Process.ResolvePath(String filename)
   at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at temp.Program.Run()

여기서 또 재미있는 것은, ^^ FileName 인자를 다음과 같이 절대 경로를 주면,

static bool Run()
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "/bin/chmod";

    Process child = Process.Start(psi);
    child.WaitForExit();
    return true;
}

이번엔 오류가 발생하지 않습니다. 왜냐하면, .NET BCL의 Process.Start는 실행 파일명이 상대 경로라면 현재 디렉터리(Environment.CurrentDirectory)에 해당 바이너리 파일이 있는지 먼저 검사하는 작업을 거치면서 CurrentDirectory 속성을 접근하게 되지만 절대 경로라면 그 작업을 생략하기 때문입니다.




이 문제를 해결하려면 어떻게 해야 할까요? 간단합니다. 해당 디렉터리가 삭제된 경우라면 Environment.CurrentDirectory에 존재하는 경로를 새롭게 설정해 줍니다.

Environment.CurrentDirectory = "/home/testuser/temp/bin/Debug";

물론 저 디렉터리는 실제로 존재하는 경로여야 합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/11/2019]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
12950정성태2/1/20226439.NET Framework: 1146. .NET 6에 추가되지 않은 Generic Math (예: INumber<T>)
12949정성태2/1/20226318.NET Framework: 1145. C# - ffmpeg(FFmpeg.AutoGen) - Codec 정보 열람 및 사용 준비파일 다운로드1
12948정성태1/30/20226422.NET Framework: 1144. C# - ffmpeg(FFmpeg.AutoGen) AVFormatContext를 이용해 ffprobe처럼 정보 출력파일 다운로드1
12947정성태1/30/20227567개발 환경 구성: 634. ffmpeg.exe - 기존 동영상 컨테이너에 다중 스트림을 추가하는 방법
12946정성태1/28/20226073오류 유형: 792. .NET Core - 로컬 개발 중에 docker 호스팅으로 바꾸는 경우 SQL 서버 접근 방법
12945정성태1/28/20226328오류 유형: 791. SQL 서버 로그인 시 localhost는 되고, 127.0.0.1로는 안 되는 문제
12944정성태1/28/20228698.NET Framework: 1143. C# - Entity Framework Core 6 개요
12943정성태1/27/20227614.NET Framework: 1142. .NET 5+로 포팅 시 플랫폼 호환성 경고 메시지(SYSLIB0006, SYSLIB0011, CA1416)파일 다운로드1
12942정성태1/27/20227878.NET Framework: 1141. XmlSerializer와 Dictionary 타입파일 다운로드1
12941정성태1/26/20229271오류 유형: 790. AKS/k8s - pod 상태가 Pending으로 지속되는 경우
12940정성태1/26/20226686오류 유형: 789. AKS에서 hpa에 따른 autoscale 기능이 동작하지 않는다면?
12939정성태1/25/20227378.NET Framework: 1140. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP3 오디오 파일 인코딩/디코딩하는 예제파일 다운로드1
12938정성태1/24/20229682개발 환경 구성: 633. Docker Desktop + k8s 환경에서 local 이미지를 사용하는 방법
12937정성태1/24/20227517.NET Framework: 1139. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 오디오(mp2) 인코딩하는 예제(encode_audio.c) [2]파일 다운로드1
12936정성태1/22/20227464.NET Framework: 1138. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 멀티미디어 파일의 메타데이터를 보여주는 예제(metadata.c)파일 다운로드1
12935정성태1/22/20227642.NET Framework: 1137. ffmpeg의 파일 해시 예제(ffhash.c)를 C#으로 포팅파일 다운로드1
12934정성태1/22/20227194오류 유형: 788. Warning C6262 Function uses '65564' bytes of stack: exceeds /analyze:stacksize '16384'. Consider moving some data to heap. [2]
12933정성태1/21/20227764.NET Framework: 1136. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP2 오디오 파일 디코딩 예제(decode_audio.c)파일 다운로드1
12932정성태1/20/20228208.NET Framework: 1135. C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c) [2]파일 다운로드1
12931정성태1/20/20226346개발 환경 구성: 632. ASP.NET Core 프로젝트를 AKS/k8s에 올리는 과정
12930정성태1/19/20226964개발 환경 구성: 631. AKS/k8s의 Volume에 파일 복사하는 방법
12929정성태1/19/20226737개발 환경 구성: 630. AKS/k8s의 Pod에 Volume 연결하는 방법
12928정성태1/18/20226884개발 환경 구성: 629. AKS/Kubernetes에서 호스팅 중인 pod에 shell(/bin/bash)로 진입하는 방법
12927정성태1/18/20226638개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/20227152오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227240개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...