linux守护进程start-stop-daemon启动服务

start-stop-daemon

#! /bin/sh

PATH=/sbin:/bin

. /lib/lsb/init-functions

do_start () {
   log_action_msg "do_start tftp here"

   if start-stop-daemon --start --background --pidfile /var/run/tftp.pid \
   --exec /home/zxc/tftp/tftps; then               
      log_action_msg "do_start succ"
      log_end_msg 0 || true
   else
      log_action_msg "do_start error"
      log_end_msg 1 || true
   fi
}

do_stop () {
   log_action_msg "do_stop tftp here"

   if start-stop-daemon start-stop-daemon --stop --name tftps; then
      log_action_msg "do_stop succ"
      log_end_msg 0 || true
   else
      log_action_msg "do_stop error"
      log_end_msg 1 || true
   fi
}

case "$1" in
   start)
      do_start
      ;;
   restart|reload|force-reload)
      echo "Error: argument '$1' not supported" >&2
      exit 3
      ;;
   stop)
      do_stop
      ;;
   status)
      status_of_proc -p /var/run/tftp.pid /home/zxc/tftp/tftps tftps \
      && exit 0 || exit $?
      ;;
   *)
      echo "Usage: $0 start|stop" >&2
      exit 3
      ;;
esac

/var/run/*.pid

#define PID_FILE "/var/run/tftp.pid"

int lock_file(int fd)
{
    struct flock fl;
    fl.l_type = F_WRLCK;
    fl.l_start = 0;
    fl.l_whence = SEEK_SET;
    fl.l_len = 0;

    return (fcntl(fd, F_SETLK, &fl));
}

int alone_runnind(void)
{
    int fd;
    char buf[16];

    fd = open(PID_FILE, O_RDWR | O_CREAT, 0666);
    if (fd < 0)
    {
        perror("open");
        exit(1);
    }

    if (lock_file(fd) < 0)
    {
        if (errno == EAGAIN)
        {
            close(fd);
            printf("alone runnind\n");
            return -1;
        }

        printf("can't lock %s: %s\n", PID_FILE, strerror(errno));
    }

    ftruncate(fd, 0);
    sprintf(buf, "%ld\n", (long)getpid());
    write(fd, buf, strlen(buf));

    close(fd);

    return 0;
}
posted @ 2019-06-28 10:07  thomas_blog  阅读(852)  评论(0编辑  收藏  举报