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)
13099정성태7/14/20227799.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자파일 다운로드1
13098정성태7/13/20226083개발 환경 구성: 647. Azure - scale-out 상태의 App Service에서 특정 인스턴스에 요청을 보내는 방법 [1]
13097정성태7/12/20225491오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228246.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226322Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20226025오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20226951.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20227888.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226709.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20225842오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226321개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225442개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228399스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20227815.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20227880.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226518개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227092.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226136.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226211.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226831개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224570오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226588.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20226923스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20225882Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226185.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226391Windows: 207. Windows Server 2022에 도입된 WSL 2
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...