Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

.NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.

간단한 EventWaitHandle 사용 코드를,

using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset, "test");

        Console.ReadLine();

        ewh.Close();
    }
}

.NET Core 콘솔 프로젝트지만 윈도우에서 실행하는 경우에는 잘 동작합니다. 반면, linux에서 실행하면 다음과 같은 식의 예외가 발생합니다.

$ dotnet ConsoleApp1.dll

Unhandled Exception: System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
   at System.Threading.EventWaitHandle..ctor(Boolean initialState, EventResetMode mode, String name)
   at ConsoleApp1.Program.Main(String[] args) in F:\ConsoleApp1\ConsoleApp1\Program.cs:line 10
Aborted (core dumped)

이해가 됩니다. 리눅스 경우 커널 이벤트 자원에 대해 "이름"을 붙여주는 기능은 없을 수 있습니다. 혹시나 싶어 회사 동료에게 물어보니, Semaphore 자원의 경우 "named"가 있다고 합니다. 오호~~~ 그렇다면 어쩌면 Semaphore의 경우에는 .NET Core도 "named semaphore"를 그대로 지원해 주지 않을까요? 그래서 소스 코드를 다음과 같이 변경했는데,

Semaphore ewh = new Semaphore(1, 2, "test");

역시나 PlatformNotSupportedException 예외가 발생합니다. 음... 그렇다면 Pinvoke를 해서라도 "named semaphore"를 어떻게든 이용해보리라... 결심하고 있는데 회사 동료가 찬물을 끼얹습니다. ^^

POSIX name semaphore does not release after process exits
; https://stackoverflow.com/questions/34756406/posix-name-semaphore-does-not-release-after-process-exits/42416684

이식성이 좋은 POSIX 표준의 세마포어는 프로세스가 비정상 종료하거나 signal에 의해 종료하는 경우, 해제되지 않는다는 것입니다.

No. POSIX semaphores are not released if the owning process crashes or is killed by signals. The waiting process will have to wait forever. You can't work around this as long as you stick with semaphores.


.NET Core 측의 이슈에도 이와 유사한 덧글이 있습니다.

Implement named synchronization primitives to be system wide
; https://github.com/dotnet/coreclr/issues/1237

POSIX named semaphores have kernel persistence: if not removed by sem_unlink, a semaphore will exist until the system is shut down.





가까운 이웃 동네인 자바를 보면 프로세스 간의 이러한 lock을 유지하기 위해 주로 "파일 lock"을 쓰는 것을 볼 수 있습니다. 예전에는 그 이유를 몰랐는데 이제야 왜 그랬는지를 알게 되는군요. ^^;

따라서, 가령 2개 이상의 프로세스가 실행되지 못하도록 하고 싶은 경우 윈도우 운영체제에서는 "named" 커널 자원을 사용해 해결할 수 있지만 리눅스의 경우에는 파일 시스템 상에 그런 목적을 위한 플래그 용도의 파일을 생성해 해결해야 합니다. 대충 다음과 같은 식으로 처리할 수 있습니다.

#if ISNETCORE
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) == true)
    {
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset, key, out createdNew);
    }
    else
    {
        string instTempFilePath = Path.Combine(Path.GetTempPath(), "test");

        try
        {
            fwh = new FileStream(instTempFilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
            if (fwh != null)
            {
                createdNew = true;
            }
        } 
        catch (Exception e)
        {
        }
    }
#else
    ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "test", out createdNew);
#endif


    if (createdNew == true)
    {
        // 첫 번째 프로세스
    }
    else
    {
        // 두 번째 프로세스
    }

그런데, 위와 같이 해도 문제가 있다고 합니다. "Path.GetTempPath()"가 반환하는 경로가 "/tmp"인데 리눅스에서는 /tmp 폴더를 주기적으로 삭제하는 daemon 프로세스가 떠 있는 경우가 있어 우리가 생성한 "test" 파일이 임의 시점에 삭제될 수가 있는 것입니다. 따라서 /var/tmp를 사용하든가, 아니면 응용 프로그램이 설치된 경로를 기준으로 임시 파일을 생성하는 것이 좋습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/21/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)
13129정성태9/27/20225485.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20228068C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226512Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227119.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/20227322.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/20227076.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
13123정성태9/8/20227505.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
13122정성태8/26/20227492.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
13121정성태8/23/20225489C/C++: 157. Golang - 구조체의 slice 필드를 Reflection을 이용해 변경하는 방법
13120정성태8/19/20226991Windows: 209. Windows NT Service에서 UI를 다루는 방법 [3]
13119정성태8/18/20226549.NET Framework: 2044. .NET Core/5+ 프로젝트에서 참조 DLL이 보관된 공통 디렉터리를 지정하는 방법
13118정성태8/18/20225435.NET Framework: 2043. WPF Color의 기본 색 영역은 (sRGB가 아닌) scRGB [2]
13117정성태8/17/20227550.NET Framework: 2042. C# 11 - 파일 범위 내에서 유효한 타입 정의 (File-local types)파일 다운로드1
13116정성태8/4/20228026.NET Framework: 2041. C# - Socket.Close 시 Socket.Receive 메서드에서 예외가 발생하는 문제파일 다운로드1
13115정성태8/3/20228391.NET Framework: 2040. C# - ValueTask와 Task의 성능 비교 [1]파일 다운로드1
13114정성태8/2/20228526.NET Framework: 2039. C# - Task와 비교해 본 ValueTask 사용법파일 다운로드1
13113정성태7/31/20227746.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
13112정성태7/30/20228166.NET Framework: 2037. C# 11 - 목록 패턴(List patterns) [1]파일 다운로드1
13111정성태7/29/20227973.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합파일 다운로드1
13110정성태7/27/20228012.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)파일 다운로드1
13109정성태7/27/20229381VS.NET IDE: 177. 비주얼 스튜디오 2022를 이용한 (소스 코드가 없는) 닷넷 모듈 디버깅 - "외부 원본(External Sources)" [1]
13108정성태7/26/20227405Linux: 53. container에 실행 중인 Golang 프로세스를 디버깅하는 방법 [1]
13107정성태7/25/20226622Linux: 52. Debian/Ubuntu 계열의 docker container에서 자주 설치하게 되는 명령어
13106정성태7/24/20226281오류 유형: 819. 닷넷 6 프로젝트의 "Conditional compilation symbols" 기본값 오류
13105정성태7/23/20227565.NET Framework: 2034. .NET Core/5+ 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 - 두 번째 이야기 [1]
13104정성태7/23/202210677Linux: 51. WSL - init에서 systemd로 전환하는 방법
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...