func Cleanup() {
	if WithCpuProfile() {
		pprof.StopCPUProfile()
		cpuOut.Close()
	}
	if WithMemProfile() {
		runtime.GC()
		writeHeapProfile(*memprofile)
		debugMemStats()
	}
}
Cleanup handles cleaning up the runtime and OS environments. This includes
tasks such as stopping the CPU profile if it is running.
package service
import (
	"flag"
	"log"
	"os"
	"os/signal"
	"runtime"
	"runtime/pprof"
	"sync"
	"syscall"
	"github.com/elastic/beats/libbeat/logp"
	"net/http"
	_ "net/http/pprof"
)
func HandleSignals(stopFunction func()) {
	var callback sync.Once
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigc
		logp.Debug("service", "Received sigterm/sigint, stopping")
		callback.Do(stopFunction)
	}()
	go ProcessWindowsControlEvents(func() {
		logp.Debug("service", "Received svc stop/shutdown request")
		callback.Do(stopFunction)
	})
}
var memprofile, cpuprofile, httpprof *string
var cpuOut *os.File
func init() {
	memprofile = flag.String("memprofile", "", "Write memory profile to this file")
	cpuprofile = flag.String("cpuprofile", "", "Write cpu profile to file")
	httpprof = flag.String("httpprof", "", "Start pprof http server")
}
func WithMemProfile() bool {
	return *memprofile != ""
}
func WithCpuProfile() bool {
	return *cpuprofile != ""
}
func BeforeRun() {
	if WithCpuProfile() {
		cpuOut, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(cpuOut)
	}
	if *httpprof != "" {
		go func() {
			logp.Info("start pprof endpoint")
			logp.Info("finished pprof endpoint: %v", http.ListenAndServe(*httpprof, nil))
		}()
	}
}