esync

Directory watching and remote syncing
Log | Files | Refs | README | LICENSE

status.go (1608B)


      1 package cmd
      2 
      3 import (
      4 	"fmt"
      5 	"os"
      6 	"path/filepath"
      7 	"strconv"
      8 	"strings"
      9 	"syscall"
     10 
     11 	"github.com/spf13/cobra"
     12 )
     13 
     14 // ---------------------------------------------------------------------------
     15 // Command
     16 // ---------------------------------------------------------------------------
     17 
     18 var statusCmd = &cobra.Command{
     19 	Use:   "status",
     20 	Short: "Check if an esync daemon is running",
     21 	Long:  "Read the PID file and report whether an esync daemon process is currently alive.",
     22 	RunE:  runStatus,
     23 }
     24 
     25 func init() {
     26 	rootCmd.AddCommand(statusCmd)
     27 }
     28 
     29 // ---------------------------------------------------------------------------
     30 // Run
     31 // ---------------------------------------------------------------------------
     32 
     33 func runStatus(cmd *cobra.Command, args []string) error {
     34 	pidPath := filepath.Join(os.TempDir(), "esync.pid")
     35 
     36 	data, err := os.ReadFile(pidPath)
     37 	if err != nil {
     38 		if os.IsNotExist(err) {
     39 			fmt.Println("No esync daemon running.")
     40 			return nil
     41 		}
     42 		return fmt.Errorf("reading PID file: %w", err)
     43 	}
     44 
     45 	pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
     46 	if err != nil {
     47 		return fmt.Errorf("invalid PID file content: %w", err)
     48 	}
     49 
     50 	process, err := os.FindProcess(pid)
     51 	if err != nil {
     52 		fmt.Println("No esync daemon running (stale PID file).")
     53 		os.Remove(pidPath)
     54 		return nil
     55 	}
     56 
     57 	// Signal 0 checks whether the process is alive without actually sending a signal.
     58 	if err := process.Signal(syscall.Signal(0)); err != nil {
     59 		fmt.Println("No esync daemon running (stale PID file).")
     60 		os.Remove(pidPath)
     61 		return nil
     62 	}
     63 
     64 	fmt.Printf("esync daemon running (PID %d)\n", pid)
     65 	return nil
     66 }