github.heygears.com/openimsdk/tools@v0.0.49/system/program/program.go (about)

     1  // Copyright © 2024 OpenIM open source community. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package program
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  	"path/filepath"
    21  	"strings"
    22  )
    23  
    24  func ExitWithError(err error) {
    25  	progName := filepath.Base(os.Args[0])
    26  	fmt.Fprintf(os.Stderr, "%s exit -1: %+v\n", progName, err)
    27  	os.Exit(-1)
    28  }
    29  
    30  func SIGTERMExit() {
    31  	progName := filepath.Base(os.Args[0])
    32  	fmt.Fprintf(os.Stderr, "Warning %s receive process terminal SIGTERM exit 0\n", progName)
    33  }
    34  
    35  // GetProcessName retrieves the name of the currently running process.
    36  // It achieves this by parsing os.Args[0], which typically contains the full path to the program.
    37  // If os.Args[0] is empty or unset for some reason, the function returns an empty string.
    38  // Note: This function assumes that os.Args contains at least the program name. This is a safe assumption under normal circumstances.
    39  func GetProcessName() string {
    40  	args := os.Args
    41  	if len(args) > 0 {
    42  		segments := strings.Split(args[0], "/")
    43  		if len(segments) > 0 {
    44  			return segments[len(segments)-1]
    45  		}
    46  	}
    47  	return ""
    48  }