pidfile.cpp 1.7 KB
Newer Older
羽飞's avatar
羽飞 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Longda on 2010
//

#include <assert.h>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <libgen.h>
#include <paths.h>
#include <sstream>
#include <string.h>
#include <unistd.h>

#include "common/log/log.h"
#include "common/os/pidfile.h"
namespace common {

29 30
std::string &getPidPath()
{
羽飞's avatar
羽飞 已提交
31 32 33 34 35
  static std::string path;

  return path;
}

36 37
void setPidPath(const char *progName)
{
羽飞's avatar
羽飞 已提交
38 39 40 41
  std::string &path = getPidPath();

  if (progName != NULL) {
    path = std::string(_PATH_TMP) + progName + ".pid";
42
  } else {
羽飞's avatar
羽飞 已提交
43 44 45 46
    path = "";
  }
}

47 48
int writePidFile(const char *progName)
{
羽飞's avatar
羽飞 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61
  assert(progName);
  std::ofstream ostr;
  int rv = 1;

  setPidPath(progName);
  std::string path = getPidPath();
  ostr.open(path.c_str(), std::ios::trunc);
  if (ostr.good()) {
    ostr << getpid() << std::endl;
    ostr.close();
    rv = 0;
  } else {
    rv = errno;
62
    std::cerr << "error opening PID file " << path.c_str() << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
63 64 65 66 67
  }

  return rv;
}

68 69
void removePidFile(void)
{
羽飞's avatar
羽飞 已提交
70 71 72 73 74 75 76 77
  std::string path = getPidPath();
  if (!path.empty()) {
    unlink(path.c_str());
    setPidPath(NULL);
  }
  return;
}

78
}  // namespace common