Browse Source

Free memory after start

世界 3 years ago
parent
commit
2ba2f0298c
1 changed files with 14 additions and 4 deletions
  1. 14 4
      cmd/sing-box/cmd_run.go

+ 14 - 4
cmd/sing-box/cmd_run.go

@@ -6,6 +6,7 @@ import (
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"os/signal"
 	"os/signal"
+	runtimeDebug "runtime/debug"
 	"syscall"
 	"syscall"
 
 
 	"github.com/sagernet/sing-box"
 	"github.com/sagernet/sing-box"
@@ -54,10 +55,10 @@ func readConfig() (option.Options, error) {
 	return options, nil
 	return options, nil
 }
 }
 
 
-func run() error {
+func create() (*box.Box, context.CancelFunc, error) {
 	options, err := readConfig()
 	options, err := readConfig()
 	if err != nil {
 	if err != nil {
-		return err
+		return nil, nil, err
 	}
 	}
 	if disableColor {
 	if disableColor {
 		if options.Log == nil {
 		if options.Log == nil {
@@ -69,12 +70,20 @@ func run() error {
 	instance, err := box.New(ctx, options)
 	instance, err := box.New(ctx, options)
 	if err != nil {
 	if err != nil {
 		cancel()
 		cancel()
-		return E.Cause(err, "create service")
+		return nil, nil, E.Cause(err, "create service")
 	}
 	}
 	err = instance.Start()
 	err = instance.Start()
 	if err != nil {
 	if err != nil {
 		cancel()
 		cancel()
-		return E.Cause(err, "start service")
+		return nil, nil, E.Cause(err, "start service")
+	}
+	return instance, cancel, nil
+}
+
+func run() error {
+	instance, cancel, err := create()
+	if err != nil {
+		return err
 	}
 	}
 	if debug.Enabled {
 	if debug.Enabled {
 		http.HandleFunc("/debug/close", func(writer http.ResponseWriter, request *http.Request) {
 		http.HandleFunc("/debug/close", func(writer http.ResponseWriter, request *http.Request) {
@@ -82,6 +91,7 @@ func run() error {
 			instance.Close()
 			instance.Close()
 		})
 		})
 	}
 	}
+	runtimeDebug.FreeOSMemory()
 	osSignals := make(chan os.Signal, 1)
 	osSignals := make(chan os.Signal, 1)
 	signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
 	signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
 	<-osSignals
 	<-osSignals