Beispiel #1
0
int daemonize(int chdir2root)
{
	switch (fork()) {
		case -1: /* error */
			return TRACKD_ERR;
		case 0:  /* child */
			break;
		default: /* parent */
			_exit(EXIT_SUCCESS);
	}

	if (setsid() == -1)
		return TRACKD_ERR;

	if (chdir2root) {
		if(chdir("/") != 0) {
			perror("chdir");
			return TRACKD_ERR;
		}
	}

	createPidFile(g_settings->pidfile);

	return TRACKD_OK;
}
// ----------------------------------------------------
// Function called when we want to start the server.
// This function expects the following parameter to be passed:
// the directory of the server we want to start and the
// command line (and its argumets) that we want to execute (basically the java
// command that we want to start the server).  The main reasons
// to have the command line passed are:
// 1. Keep the native code as minimal as possible.
// 2. Allow the administrator some flexibility in the way the
// server is started by leaving most of the logic in the command-line.
//
// This approach makes things to be closer between what is proposed
// in windows and in UNIX systems.
//
// If the instance could be started the code will write the pid of the process
// of the server in file that can be used for instance to stop the server
// (see stop.c).
//
// Returns the pid of the process of the instance if it could be started and -1
// otherwise.
// ----------------------------------------------------
int start(const char* instanceDir, char* argv[])
{
  int returnValue;
  int childPid;

  char command[COMMAND_SIZE];

  if (getCommandLine(argv, command, COMMAND_SIZE))
  {
    childPid = spawn(command, TRUE);

    if (childPid > 0)
    {
      createPidFile(instanceDir, childPid);
      returnValue = childPid;
    }
    else
    {
      debugError("Couldn't start the child process because the spawn failed.");
      returnValue = -1;
    }
  }
  else
  {
    debugError("Couldn't start the child process because the full command line could not be constructed.");
    returnValue = -1;
  }

  return returnValue;
} // start
Beispiel #3
0
void Initializer::initDaemon() {
  if (FLAGS_config_check) {
    // No need to daemonize, emit log lines, or create process mutexes.
    return;
  }

#ifndef __APPLE__
  // OSX uses launchd to daemonize.
  if (osquery::FLAGS_daemonize) {
    if (daemon(0, 0) == -1) {
      ::exit(EXIT_FAILURE);
    }
  }
#endif

  // Print the version to SYSLOG.
  syslog(
      LOG_NOTICE, "%s started [version=%s]", binary_.c_str(), OSQUERY_VERSION);

  // Check if /var/osquery exists
  if ((Flag::isDefault("pidfile") || Flag::isDefault("database_path")) &&
      !isDirectory("/var/osquery")) {
    std::cerr << CONFIG_ERROR
  }

  // Create a process mutex around the daemon.
  auto pid_status = createPidFile();
  if (!pid_status.ok()) {
    LOG(ERROR) << binary_ << " initialize failed: " << pid_status.toString();
    ::exit(EXIT_FAILURE);
  }
}
Beispiel #4
0
bool VoxMain::initialize(int argc, char** argv)
{
    if(!readUserInput(argc, argv))
        return false;

    installSignalHandler();

    if(!setToDaemon())
        return false;

    if(!setupLog())
        return false;

    if(!INIT_WIRING)
    {
        ERROR("INIT_WIRING failed!");
        return false;
    }

    if(!VoxControl::getInstance().start())
    {
        ERROR("(MAIN) failed to start controller thread");
        return false;
    }

    if(!VoxSensor::getInstance().start())
    {
        ERROR("(MAIN) failed to start sensor thread");
        return false;
    }

    if(!VoxPlayer::getInstance().start())
    {
        ERROR("(MAIN) failed to start player thread");
        return false;
    }

    if(!VoxVision::getInstance().start())
    {
        ERROR("(MAIN) failed to start vision thread");
        return false;
    }

    if(!VoxVoice::getInstance().start())
    {
        ERROR("(MAIN) failed to start voice thread");
        return false;
    }

    if(!createPidFile())
    {
        ERROR("(MAIN) pid file '%s' create failed", m_pidfile.c_str());
        return false;
    }

    return true;
}
Beispiel #5
0
int main(int argc, char** argv)
{
    printf("%s %s, Copyright 2015 by OneXSoft\n\n", APP_NAME, APP_VERSION);

    const char* cfgFile = "onecache.xml";
    if (argc == 1) {
        LOG(Logger::Message, "No config file specified. using the default config(%s)", cfgFile);
    }
    if (argc >= 2) {
        cfgFile = argv[1];
    }

    CRedisProxyCfg* cfg = CRedisProxyCfg::instance();
    if (!cfg->loadCfg(cfgFile)) {
        LOG(Logger::Error, "Failed to read config file");
        return 1;
    }

    const char* errInfo;
    if (!CRedisProxyCfgChecker::isValid(cfg, errInfo)) {
        LOG(Logger::Error, "Invalid configuration: %s", errInfo);
        return 1;
    }

    FileLogger fileLogger;
    if (fileLogger.setFileName(cfg->logFile())) {
        LOG(Logger::Message, "Using the log file(%s) output", fileLogger.fileName());
        Logger::setDefaultLogger(&fileLogger);
    }

    GlobalLogOption::__debug = cfg->debug();

    const char* pidfile = cfg->pidFile();
    bool pidfile_enabled = (strlen(pidfile) > 0);
    if (pidfile_enabled) {
        createPidFile(pidfile);
    }

    //Background
    if (cfg->daemonize()) {
        NonPortable::daemonize();
    }

    //Guard
    if (cfg->guard()) {
        NonPortable::guard(startOneCache, APP_EXIT_KEY);
    } else {
        startOneCache();
    }

    if (pidfile_enabled) {
        remove(pidfile);
    }

    return 0;
}
Beispiel #6
0
PidFile::PidFile(
  const char * path,
  const char * name,
  const char * ext
  )
  : fileName( path, name, ext ),
    osErrno( 0 )
{
  createPidFile();
}
Beispiel #7
0
void Initializer::initDaemon() const {
  if (FLAGS_config_check) {
    // No need to daemonize, emit log lines, or create process mutexes.
    return;
  }

#ifndef __APPLE__
  // OS X uses launchd to daemonize.
  if (osquery::FLAGS_daemonize) {
    if (daemon(0, 0) == -1) {
      shutdown(EXIT_FAILURE);
    }
  }
#endif

  // Print the version to SYSLOG.
  syslog(
      LOG_NOTICE, "%s started [version=%s]", binary_.c_str(), kVersion.c_str());

  // Check if /var/osquery exists
  if ((Flag::isDefault("pidfile") || Flag::isDefault("database_path")) &&
      !isDirectory(OSQUERY_HOME)) {
    std::cerr << CONFIG_ERROR;
  }

  // Create a process mutex around the daemon.
  auto pid_status = createPidFile();
  if (!pid_status.ok()) {
    LOG(ERROR) << binary_ << " initialize failed: " << pid_status.toString();
    shutdown(EXIT_FAILURE);
  }

  // Nice ourselves if using a watchdog and the level is not too permissive.
  if (!FLAGS_disable_watchdog &&
      FLAGS_watchdog_level >= WATCHDOG_LEVEL_DEFAULT &&
      FLAGS_watchdog_level != WATCHDOG_LEVEL_DEBUG) {
    // Set CPU scheduling I/O limits.
    setpriority(PRIO_PGRP, 0, 10);
#ifdef __linux__
    // Using: ioprio_set(IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE);
    syscall(SYS_ioprio_set, IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE);
#elif defined(__APPLE__)
    setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE);
#endif
  }
}
Beispiel #8
0
void Initializer::initDaemon() const {
  if (FLAGS_config_check) {
    // No need to daemonize, emit log lines, or create process mutexes.
    return;
  }

#if !defined(__APPLE__) && !defined(WIN32)
  // OS X uses launchd to daemonize.
  if (osquery::FLAGS_daemonize) {
    if (daemon(0, 0) == -1) {
      shutdown(EXIT_FAILURE);
    }
  }
#endif

  // Print the version to the OS system log.
  systemLog(binary_ + " started [version=" + kVersion + "]");

  if (!FLAGS_ephemeral) {
    if ((Flag::isDefault("pidfile") || Flag::isDefault("database_path")) &&
        !isDirectory(OSQUERY_HOME)) {
      std::cerr << CONFIG_ERROR;
    }

    // Create a process mutex around the daemon.
    auto pid_status = createPidFile();
    if (!pid_status.ok()) {
      LOG(ERROR) << binary_ << " initialize failed: " << pid_status.toString();
      shutdown(EXIT_FAILURE);
    }
  }

  // Nice ourselves if using a watchdog and the level is not too permissive.
  if (!FLAGS_disable_watchdog && FLAGS_watchdog_level >= 0) {
    // Set CPU scheduling I/O limits.
    setToBackgroundPriority();

#ifdef __linux__
    // Using: ioprio_set(IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE);
    syscall(SYS_ioprio_set, IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE);
#elif defined(__APPLE__)
    setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE);
#endif
  }
}
Beispiel #9
0
void *sfs_init(struct fuse_conn_info *conn) {
    char pidpath[PATH_MAX];

    // open syslog
    openlog(config.ident, 0, LOG_DAEMON);

    // write PID into .pid file
    // we can't do it in main(), because fuse clones this process
    snprintf(pidpath, PATH_MAX, "/var/run/syncedfs/fs/%s.pid", config.resource);
    config.pidfd = createPidFile(config.ident, pidpath, 0);

    // setup signal handlers
    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_sigaction = handleSIGUSR1;
    act.sa_flags = SA_SIGINFO;

    if (sigaction(SIGUSR1, &act, NULL) == -1)
        errMsg(LOG_ERR, "Could not setup signal handlers.");

    return NULL;
}
Beispiel #10
0
void startServer(void) {
    int pidfd;
    char pidpath[PATH_MAX];
    int lfd, cfd;
    socklen_t addrlen;
    struct sockaddr claddr;

    lfd = inetListen(config.port, 0, &addrlen);
    if (lfd == -1) {
        errMsg(LOG_ERR, "Could not listen on port %s.", config.port);
        return;
    }

    snprintf(pidpath, PATH_MAX, "/var/run/syncedfs/server/%s.pid",
            config.resource);
    pidfd = createPidFile(config.ident, pidpath, 0);
    if (pidfd == -1) {
        errMsg(LOG_ERR, "Could not create pid file %s, Exiting server.", pidpath);
        return;
    }

    errMsg(LOG_INFO, "Server booted.");

    //setup signal handler to stop handling requests
    for (;;) {
        cfd = accept(lfd, (struct sockaddr *) &claddr, &addrlen);

        if (cfd == -1) {
            errnoMsg(LOG_ERR, "Error accepting client.");
            continue;
        }
        handleClient(cfd, &claddr, &addrlen);
    }

    // delete pid file
    if (deletePidFile(pidfd, pidpath) == -1)
        errExit(LOG_ERR, "Deleting PID file '%s'", pidpath);
}
Beispiel #11
0
int main(int argc, char **argv)
{
    if (3 != argc) 
    {
        help(argc, argv);
        
        return -1;
    }
	
    int opt = -1;
    char configfile[MIN_BUFSZ] = "";
	
    while ((opt = getopt(argc, argv, "c:")) != -1) 
    {
        switch (opt) 
        {
        case 'c':
            strcpy(configfile, optarg);
            break;

        default:
            help(argc, argv);
            
            return -1;
        }
    }
	
	initServerConfig();
	
    if (-1 == loadServerConfig(configfile))
    {
        return -1;
    }
    
    if (g_Server.daemonize) 
    {
        daemonize();
    }
    
    initServer();
    
    if (g_Server.daemonize) 
    {
        createPidFile();
    }
    
	g_ListenThread = new ListenThread();
	if (NULL == g_ListenThread)
	{
		myepollLog(MY_WARNING, "new ListenThread() err");
		
		return -1;
	}

	if (-1 == g_ListenThread->Bind())
	{
	    kill(getpid(), SIGTERM);
	}

	myepollLog(MY_NOTICE, "Epoll server is running :) ... (press CTRL-C to stop)");

	poll(NULL, 0, -1);

    return 0;
}
Beispiel #12
0
int synchronize(void) {
    int pidfd;
    char pidpath[PATH_MAX];
    int logfd;
    char logpath[PATH_MAX];
    int newsync = 0;

    // make sure, that there isn't another client process for this resource
    // already running
    snprintf(pidpath, PATH_MAX, "/var/run/syncedfs/client/%s.pid",
            config.resource);
    pidfd = createPidFile(config.ident, pidpath, 0);
    if (pidfd == -1) {
        errMsg(LOG_ERR, "Could not create pid file %s, Exiting sync.", pidpath);
        return -1;
    }

    // if sync log does not exist, switch log
    snprintf(logpath, PATH_MAX, "%s/%s.sync", config.logdir, config.resource);
    errMsg(LOG_INFO, "logpath: %s", logpath);
    logfd = open(logpath, O_RDONLY);
    if (logfd == -1) {
        if (switchLog() != 0) {
            errMsg(LOG_ERR, "Could not switch log file. Stopping.");
            return -1;
        }

        logfd = open(logpath, O_RDONLY);
        if (logfd == -1) {
            errnoMsg(LOG_ERR, "Could not open log file %s", logpath);
            return -1;
        }
        newsync = 1;
    }


    // sync-id
    char id[SYNCID_MAX];
    char idpath[PATH_MAX];
    snprintf(idpath, PATH_MAX, "%s/%s.id", config.logdir, config.resource);

    // second part of the condition covers weird states after crash etc.
    if (newsync == 1 || readSyncId(id, idpath, SYNCID_MAX) != 0) {
        if (generateSyncId(id, SYNCID_MAX) != 0) {
            errMsg(LOG_ERR, "Could not get sync-id. Stopping.");
            return -1;
        }
        if (writeSyncId(id, idpath) != 0) {
            errMsg(LOG_ERR, "Could not write sync-id. Stopping.");
            return -1;
        }
    }

    // create snapshot
    if (newsync || !fileExists(config.snapshot)) {
        if (createSnapshot(config.rootdir, config.snapshot, 1) == -1) {
            errMsg(LOG_ERR, "Could not create snapshot of %s to %s Stopping.",
                    config.rootdir, config.snapshot);
            return -1;
        }
    }

    // load log
    if (loadLog(logfd) != 0) {
        errMsg(LOG_ERR, "Could not load log %s", logpath);
        return -1;
    }

    // transfer changes
    if (transfer(config.host, config.port) == -1) {
        errMsg(LOG_ERR, "Error in transfer. Exiting sync.");

        // in case of failure only delete pid file
        if (deletePidFile(pidfd, pidpath) == -1)
            errExit(LOG_ERR, "Deleting PID file '%s'", pidpath);

        return -1;
    }

    // delete snapshot
    if (deleteSnapshot(config.snapshot) == -1)
        errMsg(LOG_ERR, "Could not delete snapshot %s", config.snapshot);

    // delete syncid
    if (unlink(idpath) == -1)
        errExit(LOG_ERR, "Deleting sync-id file '%s'", idpath);

    // delete sync log
    close(logfd);
    if (unlink(logpath) == -1)
        errExit(LOG_ERR, "Deleting log file '%s'", logpath);

    // delete pid file
    if (deletePidFile(pidfd, pidpath) == -1)
        errExit(LOG_ERR, "Deleting PID file '%s'", pidpath);

    return 0;
}
Beispiel #13
0
int main(int argc, char** argv) {
    struct mg_server *server;
    char  buf[100];
    char  cert[100];
    const char* pidFile = "/var/run/checkip.pid";
    char  port[140];
    char* user = "******";
    int jail_mode = FALSE;
    int c;
    int fd = -1;

    // init variables
    pid_t process_id = 0;
    pid_t sid = 0;
    daemon_mode = FALSE;
    letsencrypt_req[0] = '\0';
    letsencrypt_resp[0] = '\0';
    strncpy(cert, "checkip-cert.pem", sizeof cert);

    initValidIP();
    jailDir[0] = '\0';

    // Get the start time
    time(&start);

    // Parse command line for "-h -p nnn -c /path/to/file"
    while((c = getopt(argc, argv, "dhj:p:u:r:R:c:")) != -1)
    {
      switch(c)
      {
      case 'c': strncpy(cert, optarg, sizeof cert);
                break;
      case 'd': daemon_mode = TRUE;
                break;
      case 'j': jail_mode = TRUE;
                char* temp_dir = optarg;
                if (!dir_exists(temp_dir)) {
                  printf("Jail root dir '%s' does not exist, or is not a directory\n", jailDir);
                  return -1;
                }
                strncpy(jailDir, realpath(temp_dir, NULL), sizeof jailDir);
                break;
      case 'r': strcpy(letsencrypt_req, optarg);
                break;
      case 'R': strcpy(letsencrypt_resp, optarg);
                break;
      case 'p': strcpy(port, optarg);
                break;
      case 'u': user = optarg;
                if (!user_exists(user)) {
                  printf("User '%s' does not exist\n", user);
                  return -1;
                }
                break;
      case 'h': usage();
		return -1;
		break;
      case '?': printf("Invalid option '%c'\n", optopt);
		usage();
		return -1;
		break;
      default:	printf("Getopt error\n");
		return -100;
      }

    }
    if (jail_mode && !daemon_mode) {
      printf("-j (chroot jail) requires -d (daemon) by specified\n");
      return -1;
    }
    strcpy(ipAddr, getIPaddr());
    strcpy(port, "80,ssl://0.0.0.0:443:");
    strncat(port, cert, (sizeof port)-strlen(port)-1);

    // Open the log
    if (daemon_mode)
      openlog(NULL, LOG_CONS | LOG_PID, LOG_DAEMON);

    // lock the pid file
    fd = createPidFile(argv[0], pidFile, 0);

    // If a daemon, fork a child process and exit the parent
    if (daemon_mode) {
      // 1. create a child process
      process_id = fork();
      if (process_id < 0) {
        log_msg(daemon_mode, "fork() failed! - exiting");
        exit(-1);
      }

      // 2. kill the parent process
      if (process_id > 0)
        exit(0);

      // 3. unmask the file mode
      umask(0);

      // 4. start a new session
      sid = setsid();
      if (sid < 0) {
        log_msg(daemon_mode, "setsid() failed! - exiting");
        exit(-1);
      }

      // 5. redirect stdin, stdout and stderr to null
      redir2null(stdin, O_RDONLY);
      redir2null(stdout, O_WRONLY);
      redir2null(stderr, O_RDWR);	// Note stderr must be r/w

      // 6. Update the PID file with the child PID
      updateChildPid(fd, (long) getpid());
    }

    // Create and configure the server
    log_msg(daemon_mode, "CheckIP version %s starting", VERSION);
    printTZ();
    log_msg(daemon_mode, "Using SSL certificate '%s'", cert);
    server = mg_create_server(NULL, ev_handler);
    mg_set_option(server, "listening_port", port);
    strcpy(buf, mg_get_option(server, "listening_port"));
    if (buf[0] == '\0') {
       log_msg(daemon_mode, "open listening ports failed - exiting");
       goto exit;
    }

    // chroot jail the process
    if (jail_mode && !isChrooted()) {
       // adjust the path
       putenv("PATH=/bin:/sbin");

       // set the new root dir
       int err = chroot(jailDir);
       if (err != 0) {
          log_msg(daemon_mode, "chroot() failed! (err %d) - exiting", errno);
          exit(-1);
       }
       log_msg(daemon_mode, "Established chroot() jail under '%s'", jailDir);

       // Set the curr dir to be within the chroot
       chdir("/");
    }

    // Trap KILL's - cause 'running' flag to be set false, HUP dumps the stats
    running = -1;
    signal(SIGINT, intHandler);
    signal(SIGTERM, intHandler);
    signal(SIGHUP, intHandler);

    // load robots.txt to robots variable
    loadRobots(jailDir);

    // load sitemap.xml to robots variable
    loadSitemap(jailDir);

    // load the GeoIP database
    initGeoIP();

    // Log LetsEncrypt settings
    if (letsencrypt_req[0] != '\0')
        log_msg(daemon_mode, "LE req = '%s'\n", letsencrypt_req);
    if (letsencrypt_resp[0] != '\0')
        log_msg(daemon_mode, "LE resp = '%s'\n", letsencrypt_resp);


    // Serve request. Hit Ctrl-C or SIGTERM to terminate the program
    mg_set_option(server, "run_as_user", user);
    if (user != NULL)
      log_msg(daemon_mode, "Server executing as user '%s'", user);
    log_msg(daemon_mode, "Listening on port %s", buf);

    while (running) {
      mg_poll_server(server, 250);
    }
    if(!daemon_mode) printf("\n");

    // Get the finish time and compute the duration
exit:
    time(&finish);

    // Cleanup, and free server instance
    mg_destroy_server(&server);

    // Close and delete the pid file;
    if (fd != -1) {
    	close(fd);
    	unlink(pidFile);
    }

    // Print stats
    print_stats(daemon_mode, start, finish, "stopping after");

    // Clean up GeoIP2
    closeGeoIP();

    if (!daemon_mode) printf("\nClean shutdown\n");

    return 0;
}
Beispiel #14
0
int XzeroDaemon::run()
{
    ::signal(SIGPIPE, SIG_IGN);

    unsigned generation = 1;
    if (const char* v = getenv("XZERO_UPGRADE")) {
        generation = atoi(v) + 1;
        unsetenv("XZERO_UPGRADE");
    }

#if defined(HAVE_SYSLOG_H)
    x0::SyslogSink::open("x0d", LOG_PID | LOG_NDELAY, LOG_DAEMON);
#endif

    if (!parse())
        return 1;

    eventHandler_ = new XzeroEventHandler(this, ev::default_loop(evFlags_));
    server_ = new x0::HttpServer(eventHandler_->loop(), generation);

    // Load core plugins
    registerPlugin(core_ = new XzeroCore(this));

#ifndef XZERO_NDEBUG
    server_->logLevel(x0::Severity::debug3);
#endif

    if (systemd_) {
        nofork_ = true;
        server_->setLogger(std::make_shared<x0::SystemdLogger>());
    } else {
        if (logTarget_ == "file") {
            if (!logFile_.empty()) {
                auto logger = std::make_shared<x0::FileLogger>(logFile_, [this]() {
                    return static_cast<time_t>(ev_now(server_->loop()));
                });
                if (logger->handle() < 0) {
                    fprintf(stderr, "Could not open log file '%s': %s\n",
                            logFile_.c_str(), strerror(errno));
                    return 1;
                }

                server_->setLogger(logger);
            } else {
                server_->setLogger(std::make_shared<x0::SystemLogger>());
            }
        } else if (logTarget_ == "console") {
            server_->setLogger(std::make_shared<x0::ConsoleLogger>());
        } else if (logTarget_ == "syslog") {
            server_->setLogger(std::make_shared<x0::SystemLogger>());
        } else if (logTarget_ == "systemd") {
            server_->setLogger(std::make_shared<x0::SystemdLogger>());
        }
    }

    server_->logger()->setLevel(logLevel_);

    if (!setupConfig()) {
        log(x0::Severity::error, "Could not start x0d.");
        return -1;
    }

    unsetenv("XZERO_LISTEN_FDS");

    if (dumpIR_)
        dumpIR();

    if (!nofork_)
        daemonize();

    if (!createPidFile())
        return -1;

    if (group_.empty())
        group_ = user_;

    if (!drop_privileges(user_, group_))
        return -1;

    if (showGreeter_) {
        printf("\n\n"
               "\e[1;37m"
               "             XXXXXXXXXXX\n"
               " XX     XX   XX       XX\n"
               "  XX   XX    XX       XX\n"
               "   XX XX     XX       XX\n"
               "    XXX      XX   0   XX - Web Server\n"
               "   XX XX     XX       XX   Version " PACKAGE_VERSION "\n"
               "  XX   XX    XX       XX\n"
               " XX     XX   XX       XX\n"
               "             XXXXXXXXXXX\n"
               "\n"
               " " PACKAGE_HOMEPAGE_URL
               "\e[0m"
               "\n\n"
              );
    }

    eventHandler_->setState(XzeroState::Running);

    int rv = server_->run();

    // remove PID-file, if exists and not in systemd-mode
    if (!systemd_ && !pidfile_.empty())
        unlink(pidfile_.c_str());

    return rv;
}
Beispiel #15
0
PidFile::PidFile( const char * fullName )
  : fileName( fullName ),
    osErrno( 0 )
{
  createPidFile();
}
Beispiel #16
0
static int
initServer ()
{
  int sfd, on = 1;
  struct sockaddr_in sa;
  arc_t *arc;

  /* Daemonize */
  if (server.conf->daemonize)
    {
      daemonize ();
      createPidFile ();
    }

  /* Init CAPI */
  arc = initCapi (server.conf);
  if (arc == NULL)
    return -1;

  /* Init server socket */
  if ((sfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      perror ("creating socket");
      return -1;
    }

  if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) == -1)
    {
      perror ("setsockopt SO_REUSEADDR");
      return -1;
    }

  memset (&sa, 0, sizeof (sa));
  sa.sin_family = AF_INET;
  sa.sin_port = htons (server.conf->port);
  sa.sin_addr.s_addr = htonl (INADDR_ANY);

  if (bind (sfd, (struct sockaddr *) &sa, sizeof (sa)) == -1)
    {
      perror ("bind");
      close (sfd);
      return -1;
    }

  if (listen (sfd, MAX_LISTEN_BACKLOG) == -1)
    {
      perror ("listen");
      close (sfd);
      return -1;
    }

  server.fd = sfd;

  /* Create arrays of client thread ids */
  server.client_tid = calloc (MAX_CLIENT_THREAD, sizeof (pthread_t));

  /* Initialize reconfig thread */
  pthread_create (&server.reconfig_tid, NULL, reconfigThread, arc);

  return 0;
}