백엔드 개발 Golang Go에서 Windows 서비스 작성

Go에서 Windows 서비스 작성

Aug 28, 2024 am 06:40 AM

Writing a Windows Service in Go

목차

  • 소개
  • Windows "서비스"란 정확히 무엇인가요?
  • 왜 Golang인가요?
  • Go로 Windows 서비스 작성
  • 서비스 설치 및 시작
  • 결론
  • 완전한 코드

소개

안녕하세요 개발자 여러분, 오랜만에 윈도우 같은 글을 작성해봤습니다. 그래서 오늘은 Go에서 Windows 서비스 애플리케이션을 작성하는 방법을 안내해 드리고자 합니다. 네, 맞습니다. 바둑 언어입니다. 이 튜토리얼 블로그에서는 Windows 서비스 애플리케이션에 대한 몇 가지 기본 사항을 다룰 것이며, 후반부에서는 일부 정보를 파일에 기록하는 Windows 서비스용 코드를 작성하는 간단한 코드를 안내하겠습니다. 더 이상 고민하지 말고 시작해 보세요...!

Windows "서비스"란 정확히 무엇입니까?

Windows 서비스 애플리케이션(일명 Windows 서비스)은 백그라운드에서 실행되는 작은 애플리케이션입니다. 일반 Windows 응용 프로그램과 달리 GUI나 어떤 형태의 사용자 인터페이스도 없습니다. 이러한 서비스 응용 프로그램은 컴퓨터가 부팅될 때 실행되기 시작합니다. 실행 중인 사용자 계정에 관계없이 실행됩니다. 수명 주기(시작, 중지, 일시 중지, 계속 등)는 SCM(서비스 제어 관리자)이라는 프로그램에 의해 제어됩니다.

따라서 우리는 SCM이 Windows 서비스와 상호 작용하고 수명 주기를 관리하는 방식으로 Windows 서비스를 작성해야 한다는 것을 이해할 수 있습니다.

왜 골랭인가?

Windows 서비스 작성 시 Go를 고려할 수 있는 몇 가지 요소가 있습니다.

동시성

Go의 동시성 모델을 사용하면 더 빠르고 리소스 효율적인 처리가 가능합니다. Go의 고루틴을 사용하면 차단이나 교착 상태 없이 멀티 태스킹을 수행할 수 있는 애플리케이션을 작성할 수 있습니다.

간단

전통적으로 Windows 서비스는 C++ 또는 C(때로는 C#)를 사용하여 작성되어 코드가 복잡할 뿐만 아니라 DX(개발자 경험)도 좋지 않습니다. Go의 Windows 서비스 구현은 간단하며 모든 코드 줄이 의미가 있습니다.

정적 바이너리

"파이썬처럼 더 간단한 언어를 사용해 보는 건 어떨까요?"라고 물을 수도 있습니다. 그 이유는 Python의 해석 특성 때문입니다. Go는 Windows 서비스가 효율적으로 작동하는 데 필수적인 정적으로 연결된 단일 파일 바이너리로 컴파일합니다. Go 바이너리에는 런타임/인터프리터가 필요하지 않습니다. Go 코드는 크로스 컴파일도 가능합니다.

낮은 수준의 액세스

Go는 가비지 수집 언어이기는 하지만 하위 수준 요소와 상호 작용할 수 있는 견고한 지원을 제공합니다. go에서 win32 API와 일반 시스템 호출을 쉽게 호출할 수 있습니다.

알겠습니다. 정보는 충분합니다. 코딩해보자...

Go로 Windows 서비스 작성

이 코드 연습에서는 사용자가 Go 구문에 대한 기본 지식이 있다고 가정합니다. 그렇지 않다면 A Tour of Go를 통해 배울 수 있습니다.

  • 먼저 프로젝트 이름을 정하겠습니다. 내 이름을 cosmic/my_service로 지정하겠습니다. go.mod 파일을 생성하고,
PS C:\> go mod init cosmic/my_service
로그인 후 복사
  • 이제 golang.org/x/sys 패키지를 설치해야 합니다. 이 패키지는 Windows OS 관련 애플리케이션에 대한 Go 언어 지원을 제공합니다.
PS C:\> go get golang.org/x/sys
로그인 후 복사

참고: 이 패키지에는 Mac OS 및 Linux와 같은 UNIX 기반 OS에 대한 OS 수준 Go 언어 지원도 포함되어 있습니다.

  • main.go 파일을 생성합니다. main.go 파일에는 Go 애플리케이션/서비스의 진입점 역할을 하는 주요 기능이 포함되어 있습니다.

  • 서비스 인스턴스를 생성하려면 golang.org/x/sys/windows/svc에서 핸들러 인터페이스를 구현하는 Service Context라는 항목을 작성해야 합니다.

인터페이스 정의는 다음과 같습니다

type Handler interface {
    Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32)
}
로그인 후 복사

Execute 함수는 서비스 시작 시 패키지 코드에 의해 호출되며, Execute가 완료되면 서비스가 종료됩니다.

수신 전용 채널 r에서 서비스 변경 요청을 읽고 그에 따라 조치합니다. 또한 전송 전용 채널에 신호를 보내 서비스를 최신 상태로 유지해야 합니다. args 매개변수에 선택적 인수를 전달할 수 있습니다.

종료 시 성공적으로 실행되면 종료 코드가 0으로 반환될 수 있습니다. 이를 위해 svcSpecificEC를 사용할 수도 있습니다.

  • 이제 서비스 컨텍스트 역할을 할 myService라는 유형을 만듭니다.
type myService struct{}
로그인 후 복사
  • myService 유형을 생성한 후 위에서 언급한 Execute를 메소드로 추가하여 Handler 인터페이스를 구현합니다.
func (m *myService) Execute(args []string, r <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
    // to be filled
}
로그인 후 복사
  • 이제 핸들러 인터페이스를 성공적으로 구현했으므로 실제 로직 작성을 시작할 수 있습니다.

저희 서비스가 SCM에서 받을 수 있는 신호로 상수를 만듭니다.

const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
로그인 후 복사

Our main goal is the log some data every 30 seconds. So we need to define a thread safe timer for that.

tick := time.Tick(30 * time.Second)
로그인 후 복사

So, we have done all the initialization stuffs. It's time to send START signal to the SCM. we're going to do exactly that,

status <- svc.Status{State: svc.StartPending}
status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
로그인 후 복사

Now we're going to write a loop which acts as a mainloop for our application. Handling events in loop makes our application never ending and we can break the loop only when the SCM sends STOP or SHUTDOWN signal.

loop:
    for {
        select {
        case <-tick:
            log.Print("Tick Handled...!")
        case c := <-r:
            switch c.Cmd {
            case svc.Interrogate:
                status <- c.CurrentStatus
            case svc.Stop, svc.Shutdown:
                log.Print("Shutting service...!")
                break loop
            case svc.Pause:
                status <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
            case svc.Continue:
                status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
            default:
                log.Printf("Unexpected service control request #%d", c)
            }
        }
    }
로그인 후 복사

Here we used a select statement to receive signals from channels. In first case, we handle the Timer's tick signal. This case receives signal every 30 seconds, as we declared before. We log a string "Tick Handled...!" in this case.

Secondly, we handle the signals from SCM via the receive-only r channel. So, we assign the value of the signal from r to a variable c and using a switch statement, we can handle all the lifecycle event/signals of our service. We can see about each lifecycle below,

  1. svc.Interrogate - Signal requested by SCM on a timely fashion to check the current status of the service.
  2. svc.Stop and svc.Shutdown - Signal sent by SCM when our service needs to be stopped or Shut Down.
  3. svc.Pause - Signal sent by SCM to pause the service execution without shutting it down.
  4. svc.Continue - Signal sent by SCM to resume the paused execution state of the service.

So, when on receiving either svc.Stop or svc.Shutdown signal, we break the loop. It is to be noted that we need to send STOP signal to the SCM to let the SCM know that our service is stopping.

status <- svc.Status{State: svc.StopPending}
return false, 1
로그인 후 복사
  • Now we write a function called runService where we enable our service to run either in Debug mode or in Service Control Mode.

Note: It's super hard to debug Windows Service Applications when running on Service Control Mode. That's why we are writing an additional Debug mode.

func runService(name string, isDebug bool) {
    if isDebug {
        err := debug.Run(name, &myService{})
        if err != nil {
            log.Fatalln("Error running service in debug mode.")
        }
    } else {
        err := svc.Run(name, &myService{})
        if err != nil {
            log.Fatalln("Error running service in debug mode.")
        }
    }
}
로그인 후 복사
  • Finally we can call the runService function in our main function.
func main() {

    f, err := os.OpenFile("debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalln(fmt.Errorf("error opening file: %v", err))
    }
    defer f.Close()

    log.SetOutput(f)
    runService("myservice", false) //change to true to run in debug mode
}
로그인 후 복사

Note: We are logging the logs to a log file. In advanced scenarios, we log our logs to Windows Event Logger. (phew, that sounds like a tongue twister ?)

  • Now run go build to create a binary '.exe'. Optionally, we can optimize and reduce the binary file size by using the following command,
PS C:\> go build -ldflags "-s -w"
로그인 후 복사

Installing and Starting the Service

For installing, deleting, starting and stopping our service, we use an inbuilt tool called sc.exe

To install our service, run the following command in powershell as Administrator,

PS C:\> sc.exe create MyService <path to your service_app.exe>
로그인 후 복사

To start our service, run the following command,

PS C:\> sc.exe start MyService
로그인 후 복사

To delete our service, run the following command,

PS C:\> sc.exe delete MyService
로그인 후 복사

You can explore more commands, just type sc.exe without any arguments to see the available commands.

Conclusion

As we can see, implementing Windows Services in go is straightforward and requires minimal implementation. You can write your own windows services which acts as a web server and more. Thanks for reading and don't forget to drop a ❤️.

Complete Code

Here is the complete code for your reference.

// file: main.go

package main

import (
    "fmt"
    "golang.org/x/sys/windows/svc"
    "golang.org/x/sys/windows/svc/debug"
    "log"
    "os"
    "time"
)

type myService struct{}

func (m *myService) Execute(args []string, r <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {

    const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
    tick := time.Tick(5 * time.Second)

    status <- svc.Status{State: svc.StartPending}

    status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}

loop:
    for {
        select {
        case <-tick:
            log.Print("Tick Handled...!")
        case c := <-r:
            switch c.Cmd {
            case svc.Interrogate:
                status <- c.CurrentStatus
            case svc.Stop, svc.Shutdown:
                log.Print("Shutting service...!")
                break loop
            case svc.Pause:
                status <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
            case svc.Continue:
                status <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
            default:
                log.Printf("Unexpected service control request #%d", c)
            }
        }
    }

    status <- svc.Status{State: svc.StopPending}
    return false, 1
}

func runService(name string, isDebug bool) {
    if isDebug {
        err := debug.Run(name, &myService{})
        if err != nil {
            log.Fatalln("Error running service in debug mode.")
        }
    } else {
        err := svc.Run(name, &myService{})
        if err != nil {
            log.Fatalln("Error running service in debug mode.")
        }
    }
}

func main() {

    f, err := os.OpenFile("E:/awesomeProject/debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalln(fmt.Errorf("error opening file: %v", err))
    }
    defer f.Close()

    log.SetOutput(f)
    runService("myservice", false)
}
로그인 후 복사

위 내용은 Go에서 Windows 서비스 작성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Golang vs. Python : 성능 및 확장 성 Golang vs. Python : 성능 및 확장 성 Apr 19, 2025 am 12:18 AM

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Golang 및 C : 동시성 대 원시 속도 Golang 및 C : 동시성 대 원시 속도 Apr 21, 2025 am 12:16 AM

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

GOT GO로 시작 : 초보자 가이드 GOT GO로 시작 : 초보자 가이드 Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity, 효율성, 및 콘크리 론 피처

Golang vs. C : 성능 및 속도 비교 Golang vs. C : 성능 및 속도 비교 Apr 21, 2025 am 12:13 AM

Golang은 빠른 개발 및 동시 시나리오에 적합하며 C는 극도의 성능 및 저수준 제어가 필요한 시나리오에 적합합니다. 1) Golang은 쓰레기 수집 및 동시성 메커니즘을 통해 성능을 향상시키고, 고전성 웹 서비스 개발에 적합합니다. 2) C는 수동 메모리 관리 및 컴파일러 최적화를 통해 궁극적 인 성능을 달성하며 임베디드 시스템 개발에 적합합니다.

Golang의 영향 : 속도, 효율성 및 단순성 Golang의 영향 : 속도, 효율성 및 단순성 Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

Golang vs. Python : 주요 차이점과 유사성 Golang vs. Python : 주요 차이점과 유사성 Apr 17, 2025 am 12:15 AM

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

Golang 및 C : 성능 상충 Golang 및 C : 성능 상충 Apr 17, 2025 am 12:18 AM

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

공연 경주 : 골랑 대 c 공연 경주 : 골랑 대 c Apr 16, 2025 am 12:07 AM

Golang과 C는 각각 공연 경쟁에서 고유 한 장점을 가지고 있습니다. 1) Golang은 높은 동시성과 빠른 발전에 적합하며 2) C는 더 높은 성능과 세밀한 제어를 제공합니다. 선택은 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.

See all articles