Microsoft MVP성태의 닷넷 이야기
Linux: 18. C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법 [링크 복사], [링크+제목 복사]
조회: 16153
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법

검색해 보면 ASP.NET Core Generic Host를 기반으로 데몬 프로세스 만드는 방법이 공개되어 있습니다.

Creating a Daemon with .NET Core (Part 1)
; https://www.wintellect.com/creating-a-daemon-with-net-core-part-1/

Creating a Daemon with .NET Core (Part 2) 
; https://www.wintellect.com/creating-a-daemon-with-net-core-part-2/

물론 저렇게 만들어도 되지만, 간단한 데몬을 만드는 경우라면 가능한 별다른 모듈에 대한 의존성 없이 단일 dll로 만드는 방법도 고려해 볼 수 있습니다. 시작은, 프로그램이 종료하지 못하도록 막고 있기만 하면 됩니다.

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

    ewh.WaitOne();
}

이렇게 만든 프로그램을 "/etc/systemd/system"에 등록하면,

라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정
; https://www.sysnet.pe.kr/2/0/11374

// $ ls -l /usr/lib/systemd/system
// $ ls -l /etc/systemd/system
// $ systemctl list-unit-files

$ cat /etc/systemd/system/dotnet-testd.service 

[Unit]
Description=testd.dll running on Unix 3.10.0.957

[Service]
WorkingDirectory=/home/tusr/testd/bin
ExecStart=/usr/share/dotnet/dotnet /home/tusr/testd/bin/testd.dll
KillSignal=SIGINT
SyslogIdentifier=dotnet-testd

[Install]
WantedBy=multi-user.target

이후부터 systemctl 명령을 이용해 NT 서비스처럼 daemon으로 실행시킬 수 있습니다.

[컴퓨터 시작 시 서비스가 로드하도록 등록]
$ sudo systemctl enable dotnet-testd

[서비스 지금 시작]
$ sudo systemctl start dotnet-testd

그런데 종료가 문제입니다. 우선 systemctl의 종료 명령에는 2가지가 있습니다.

[service 파일에 등록한 KillSignal로 종료, 이번 예제에서는 SIGINT 발생]
sudo systemctl stop dotnet-testd

[프로세스 종료]
sudo systemctl kill dotnet-testd

이 중에서 "kill" 명령어의 대응은 AppDomain.CurrentDomain.ProcessExit로 처리할 수 있습니다.

AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
    CleanupResources();
    WriteLog("Exited gracefully!");
};

그런데, 이것만 하게 되면 systemctl stop 명령어에 대해서는 반응하지 않고 그냥 종료해 버립니다.

sudo systemctl stop dotnet-testd
    (ProcessExit 없이 종료)

sudo systemctl kill dotnet-testd
    ProcessExit 이벤트 발생

따라서 systemctl stop에 대한 처리를 위해 Console.CancelKeyPress를 다음과 같이 추가할 수 있습니다.

// SIGINT에 반응
Console.CancelKeyPress += (s, e) =>
{
    WriteLog("stopped");
};

// 프로세스 종료에 반응
AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
    CleanupResources();
    WriteLog("Exited gracefully!");
};

위와 같이 각각 이벤트를 등록한 경우 systemctl 명령에 대해 다음과 같은 식의 로그를 확인할 수 있습니다.

sudo systemctl stop dotnet-testd
    Jun 24 21:38:33 centos7 dotnet-testd: stopped

sudo systemctl kill dotnet-testd
    Jun 24 21:48:49 centos7 dotnet-testd: Exited gracefully!

2가지 모두 반응했지만 재미있는 것은 SIGINT의 경우 ProcessExit 이벤트가 발생하지 않는다는 특이점이 있습니다. 만약 CancelKeyPress에서 ProcessExit로 흐르게 하고 싶다면 Cancel 속성을 true로 설정한 다음, EventWaitHandle을 시그널시켜서 프로세스를 종료하게 해 자연스럽게 ProcessExit가 발생하도록 만들 수 있습니다.

Console.CancelKeyPress += (s, e) =>
{
    WriteLog("stopped");
    e.Cancel = true;
    ewh.Set();
};

AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
    CleanupResources();
    WriteLog("Exited gracefully!");
};

따라서 각각의 종료에 대해 로그는 다음과 같이 바뀝니다.

sudo systemctl stop dotnet-testd
    Jun 24 21:41:57 centos7 dotnet-testd: stopped
    Jun 24 21:41:57 centos7 dotnet-testd: Exited gracefully!

sudo systemctl kill dotnet-testd
    Jun 24 21:41:08 centos7 dotnet-testd: Exited gracefully!




부가적으로, 서비스 스스로 install/uninstall을 하도록 다음과 같은 식의 처리도 추가해 주면 좋을 것입니다.

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

    if (args.Length >= 1)
    {
        string netDllPath = typeof(Program).Assembly.Location;
        if (args[0] == "--install" || args[0] == "-i")
        {
            InstallService(netDllPath, true);
        }
        else if (args[0] == "--uninstall" || args[0] == "-u")
        {
            InstallService(netDllPath, false);
        }
        return;
    }

    // ...[생략]...

    ewh.WaitOne();
}

static int InstallService(string netDllPath, bool doInstall)
{
    // 업데이트 2021-04-22
    // KillSignal=SIGINT 제거
    // KillMode=mixed 추가
    string serviceFile = @"
[Unit]
Description={0} running on {1}

[Service]
WorkingDirectory={2}
ExecStart={3} {4}
SyslogIdentifier={5}
KillMode=mixed

[Install]
WantedBy=multi-user.target
";

    string dllFileName = Path.GetFileName(netDllPath);
    string osName = Environment.OSVersion.ToString();

    FileInfo fi = null;

    try
    {
        fi = new FileInfo(netDllPath);
    }
    catch { }

    if (doInstall == true && fi != null && fi.Exists == false)
    {
        WriteLog("NOT FOUND: " + fi.FullName);
        return 1;
    }

    string serviceName = "dotnet-" + Path.GetFileNameWithoutExtension(dllFileName).ToLower();

    string exeName = Process.GetCurrentProcess().MainModule.FileName;

    string workingDir = Path.GetDirectoryName(fi.FullName);
    string fullText = string.Format(serviceFile, dllFileName, osName, workingDir,
            exeName, fi.FullName, serviceName);

    string serviceFilePath = $"/etc/systemd/system/{serviceName}.service";

    if (doInstall == true)
    {
        File.WriteAllText(serviceFilePath, fullText);
        WriteLog(serviceFilePath + " Created");
        ControlService(serviceName, "enable");
        ControlService(serviceName, "start");
    }
    else
    {
        if (File.Exists(serviceFilePath) == true)
        {
            ControlService(serviceName, "stop");
            File.Delete(serviceFilePath);
            WriteLog(serviceFilePath + " Deleted");
        }
    }

    return 0;
}

이 정도면 거의 틀을 갖췄군요. ^^ 이제 빌드하고 testd.dll과 testd.runtimeconfig.json 파일만 리눅스 시스템에 복사하면 서비스로써 완벽하게 동작할 수 있습니다.

[서비스 등록 및 시작]
$ sudo dotnet ./test.dll --install

[서비스 해제]
$ sudo dotnet ./test.dll --uninstall

[서비스 시작]
$ sudo systemctl start dotnet-testd

[서비스 중지-1]
$ sudo systemctl stop dotnet-testd

[서비스 중지-2]
$ sudo systemctl kill dotnet-testd

이 상태에서 여러분들의 업무 코드만 추가하면 됩니다. ^^ (그나저나 제가 리눅스에 잘 모르는 상태에서 만든 것이므로, 혹시 더 좋은 예제 코드가 있다면 덧글 부탁드립니다. ^^)

(이 글의 예제 프로젝트 코드는 github에 올려두었습니다.)





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/7/2021]

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

비밀번호

댓글 작성자
 



2019-09-06 09시01분
정성태
2021-02-26 05시41분
Creating a Windows Service with C#/.NET5
; https://devblogs.microsoft.com/ifdef-windows/creating-a-windows-service-with-c-net5/

[.NET] .NET6 로 Windows Service 만들기 (2022.08.08)
; https://blog.naver.com/vactorman/222842433947
정성태
2021-04-21 05시53분
[행인1] netcore3.1에서 systemctl stop 으로 실행하면 SIGINT 발생해서 cancelkey 이벤트가 들어왔는데,
net5로 프로젝트 업그레이드 이후엔 cancelkey 이벤트가 들어오지 않는데 원인을 아실까요ㅠ?
[guest]
2021-04-21 10시12분
.NET 5에서 SIGINT가 CancelKeyPress로 안 되는 것을 확인했습니다. 그런데, ^^; 답이 안 나오는군요. 아무래도 github의 dotnet repo에 직접 이슈를 제기하는 것이 좋을 듯합니다.
정성태
2021-04-22 05시26분
아래의 내용에 덧글을 달아주신 분이 해결 방법을 제시했습니다.

C# - Generic Host를 이용해 .NET 5로 리눅스 daemon 프로그램 만드는 방법
; https://www.sysnet.pe.kr/2/0/12608#14927

따라서, 현재 만들어 두신 소스 코드에서 다음의 serviceFile 문자열만,

https://github.com/stjeong/DotNetSamples/blob/master/NetCore/testd/Program.cs#L84

바꿔서 설정하시면 됩니다. (물론, 기존 등록된 service 파일의 경우 KillSignal=SIGINT 값을 삭제하고, KillMode=mixed 설정을 추가해도 됩니다.)

바뀐 소스 코드의 경우, systemctl stop/kill 모두 AppDomain.CurrentDomain.ProcessExit 이벤트 핸들러가 실행이 되는 것을 확인했습니다.
정성태
2023-01-27 08시24분
정성태

1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...
NoWriterDateCnt.TitleFile(s)
13247정성태2/7/20234962VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234085개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234633.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20233986VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234855디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234296디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233825디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20233985디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233627디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235637.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235322.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20234968개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234510개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235559개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20236901오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234699스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233615오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234031개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20234971.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235118.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234822개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234495.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233747개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234091Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234284오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20233934개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...