Ejemplo n.º 1
0
int main() {
    struct sigaction sa;

    daemonize("reaconfig");
    already_running();

    // 处理sigterm信号 (kill -15 pid)
    sa.sa_handler = sigterm;
    sigemptyset(&sa.sa_mask);
    // 屏蔽SIGHUP
    sigaddset(&sa.sa_mask, SIGHUP);
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);

    // HUP信号处理 (kill -1 pid)
    sa.sa_handler = sighup;
    sigemptyset(&sa.sa_mask);
    // 屏蔽SIGTERM
    sigaddset(&sa.sa_mask, SIGTERM);
    sa.sa_flags = 0;
    sigaction(SIGHUP, &sa, NULL);

    // sleep 不是信号可重入的?
    // 注意,sleep在进程接受到非忽略的信号后将立即返回
    sleep(100000);
    /* 
    while (1) {
        syslog(LOG_INFO, "getc wait");
        //getc(stdin);
    }
    */
}
bool QGenieSingleProcessHandler::tryCreate()
{
#ifdef Q_OS_WIN32
    if(mSharedMemory.create(2) )
#else
    QString file_to_lock = NETGEAR_DIR;//QApplication::applicationDirPath();
    file_to_lock += "/";
    file_to_lock += LAUNCH_SINGLEINSTANCE_LOCKFILE;

    if(
            already_running(file_to_lock.toStdString().c_str()) == 0
            )
#endif
    {
        qApp->processEvents();
        return true;
    }
    else
    {

        qDebug("NETGEARGenie is already running!");

        QLaunchSemaphore sem;
        sem.release(2);
        return false;
    }
    return false;
}
Ejemplo n.º 3
0
int
main(int argc, char *argv[])
{
	int					err;
	pthread_t			tid;
	char				*cmd;
	struct sigaction	sa;

	if ((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else
		cmd++;

	/*
	 * Become a daemon.
	 */
	daemonize(cmd);

	/*
	 * Make sure only one copy of the daemon is running.
	 */
	if (already_running("/var/run/daemon.pid")) {
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}

	/*
	 * Restore SIGHUP default and block all signals.
	 */
	sa.sa_handler = SIG_DFL;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if (sigaction(SIGHUP, &sa, NULL) < 0){
		printf("main: can't restore SIGHUP default");
		exit(1);
	}
	sigfillset(&mask);
	if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0){
		perror("pthread_sigmask");
		exit(1);
	}

	/*
	 * Create a thread to handle SIGHUP and SIGTERM.
	 */
	err = pthread_create(&tid, NULL, thr_fn, 0);
	if (err != 0){
		perror("pthread_create:");
		exit(1);
	}

	/*
	 * Proceed with the rest of the daemon.
	 */
	while(1){
		sleep(30);
		syslog(LOG_INFO, "sleep again...");
	}
	exit(0);
}
Ejemplo n.º 4
0
int main(int argc, char** argv)
{
	int err;
	pthread_t tid;
	char* cmd;
	struct sigaction sa;

	if((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else 
		cmd++;
	//Become a daemon
	if(already_running())
	{
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}
	//restore SIGHUP default and block all signals
	sa.sa_handler = SIG_DFL;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if(sigaction(SIGHUP, &sa, NULL) < 0)
		err_quit("%s: cannot restore SIGHUP default");
	sigfillset(&mask);
	if((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
		err_exit(err, "SIG_BLOCK error");

	//create a thread to handle SIGHUP and SIGTERM
	err = pthread_create(&tid, NULL, thr_fn, 0);
	if(err != 0)
		err_exit(err, "cannot create thread");
	exit(0);
}
Ejemplo n.º 5
0
int
main(int argc, char* argv[])
{
  FILE *fp= NULL;
  pid_t process_id = 0;
  pid_t sid = 0;
  unsigned long iteration = 0;

  configure(&config_info);

  daemonize("oraccd", &config_info);

  if (already_running(&config_info)) {
    fprintf(config_info.logfp, "oraccd-build already running\n");
    exit(1);
  }

  while (1)
    {
      /* Don't block context switches, let the process sleep for some time. */
      sleep(1);
      fprintf(config_info.logfp, "oraccd iteration %lu ...\n", iteration++);
      fflush(config_info.logfp);
      /* Implement and call some function that does core work for this daemon. */
      q();
    }
  fclose(fp);

  return (0);
}
Ejemplo n.º 6
0
void daemonize(const char* cmd) {
    int i, fd0, fd1, fd2;
    pid_t pid;
    struct rlimit rl;
    struct sigaction sa;

    // 清空创建文件mask
    umask(0);

    if ((pid = fork()) < 0) {
        err_quit("cannot fork");
    } else if (pid != 0) {
        printf("[parent]exit\n");
        exit(0);
    }

    // 很重要,脱离当前控制终端
    setsid();

    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGHUP, &sa, NULL);

    if ((pid = fork()) < 0) {
        err_quit("cannot fork 2", cmd);
    } else if (pid != 0) {
        printf("[child]exit\n");
        exit(0);
    }

    // change pwd
    chdir("/");

    // 关闭文件描述符
    getrlimit(RLIMIT_NOFILE, &rl);
    if (rl.rlim_max == RLIM_INFINITY) {
        rl.rlim_max = 1024;
    }
    for (i = 3; i < rl.rlim_max; i++) {
        close(i);
    }

    // 保证单一实例
    // 必须在前面的关闭描述符后执行, 在重定向标准io前执行
    printf("check file lock\n");
    already_running();
  
    // 0, 1, 2重定向到/dev/null
    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);

    // 打开系统日志文件
    openlog(cmd, LOG_CONS, LOG_DAEMON);
    // 本机ubuntu日志路径 /var/log/syslog
    syslog(LOG_INFO, "daemon started");
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    int                 err;
    pthread_t           tid;
    char                *cmd;
    struct sigaction    sa;

    if ((cmd = strrchr(argv[0], '/')) == NULL)
        cmd = argv[0];
    else
        cmd++;

    /*
     * Become a daemon.
     */
    daemonize(cmd);

    /*
     * Make sure only one copy of the daemon is running.
     */
    if (already_running()) {
        syslog(LOG_ERR, "daemon already running");
        exit(1);
    }

    /*
     * Restore SIGHUP default and block all signals.
     */
    sa.sa_handler = SIG_DFL;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL) < 0) {
        fprintf(stderr, "%s: can't restore SIGHUP default", cmd);
        exit(0);
    }
    sigfillset(&mask);
    if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0) {
        fprintf(stderr, "SIG_BLOCK error");
        exit(0);
    }

    /*
     * Create a thread to handle SIGHUP and SIGTERM.
     */
    err = pthread_create(&tid, NULL, thr_fn, 0);
    if (err != 0) {
        fprintf(stderr, "can't create thread");
        exit(0);
    }

    /*
     * Proceed with the rest of the daemon.
     */
    /* ... */
    return 0;
}
Ejemplo n.º 8
0
int
main(int argc, char *argv[])
{
	int					err;
	pthread_t			tid;
	char				*cmd;
	struct sigaction	sa;

	if ((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else
		cmd++;

	/*
	 * Become a daemon.初始化守护进程
	 */
	daemonize(cmd);

	/*
	 * Make sure only one copy of the daemon is running.
	 * 确保该守护线程只有一个副本在运行
	 */
	if (already_running()) {
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}

	/*
	 * Restore SIGHUP default and block all signals.
	 * 恢复SIGHUP信号的系统默认处理方式;阻塞所有信号
	 */
	sa.sa_handler = SIG_DFL;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if (sigaction(SIGHUP, &sa, NULL) < 0)
		err_quit("%s: can't restore SIGHUP default");
	sigfillset(&mask);
	if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
		err_exit(err, "SIG_BLOCK error");

	/*
	 * Create a thread to handle SIGHUP and SIGTERM.
	 * 创建一个线程等待SIGHUP和SIGTERM;若接收到SIGHUP则重读配置文件
	 */
	err = pthread_create(&tid, NULL, thr_fn, 0);
	if (err != 0)
		err_exit(err, "can't create thread");

	/*
	 * Proceed with the rest of the daemon.
	 */
	/* ... */
	exit(0);
}
Ejemplo n.º 9
0
Archivo: 13-4.c Proyecto: klion26/APUE
int main(int argc, char* argv[])
{
	char *cmd;
	struct sigaction sa;

	if((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else
		++cmd;

	/*
	 * Become a daemon
	 */
	daemonize(cmd);

	/*
	 * Make sure only one copy of the daemon is running.
	 */
	if(already_running())
	{
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}

	/*
	 * Restore SIGHUP default and block all signals.
	 */
	sa.sa_handler = sigterm;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGHUP);
	sa.sa_flags = 0;
	if(sigaction(SIGTERM, &sa, NULL) < 0)
	{
		syslog(LOG_ERR, "can't catch SIGTERM: %s", strerror(errno));
		exit(1);
	}
	sa.sa_handler = sighub;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGTERM);
	sa.sa_flags = 0;
	if(sigaction(SIGHUP, &sa, NULL) < 0)
	{
		syslog(LOG_ERR, "can't catch SIGHUP: %s", strerror(errno));
		exit(1);
	}
	
	/*
	 * Proceed with the rest of the daemon.
	 */

	/* ... */
	exit(0);
}
Ejemplo n.º 10
0
int
main(int argc, char *argv[])
{
	char				*cmd;
	struct sigaction	sa;

	if ((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else
		cmd++;

	/*
	 * Become a daemon.
	 */
	daemonize(cmd);

	/*
	 * Make sure only one copy of the daemon is running.
	 */
	if (already_running("/var/run/daemon.pid")) {
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}
	
	/*
	 * Handle signals of interest.
	 */
	sa.sa_handler = sigterm;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGHUP);
	sa.sa_flags = 0;
	if (sigaction(SIGTERM, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGTERM: %s", strerror(errno));
		exit(1);
	}
	sa.sa_handler = sighup;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGTERM);
	sa.sa_flags = 0;
	if (sigaction(SIGHUP, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGHUP: %s", strerror(errno));
		exit(1);
	}

	/*
	 * Proceed with the rest of the daemon.
	 */
	while(1){
		printf("SLEEP AGIAN\n");
		sleep(10);
	}
	exit(0);
}
Ejemplo n.º 11
0
int main(int argc, char const *argv[])
{
    daemonize("daemonize");
    /*
     * Make sure only one copy of the daemon is running.
     */
    if (already_running()) {
        syslog(LOG_ERR, "daemon already running");
        exit(1);
    }
    printf("now go to sleep\n");
    sleep(10);
    return 0;
}
Ejemplo n.º 12
0
/* If a locked pidfile exists, issue a warning message and, unless
 * ignore_existing_pidfile() has been called, terminate the program. */
void
die_if_already_running(void)
{
    pid_t pid = already_running();
    if (pid) {
        if (!overwrite_pidfile) {
            ovs_fatal(0, "%s: already running as pid %ld",
                      get_pidfile(), (long int) pid);
        } else {
            VLOG_WARN("%s: %s already running as pid %ld",
                      get_pidfile(), program_name, (long int) pid);
        }
    }
}
Ejemplo n.º 13
0
int main(int argc, char *argv[]) {
  int              err, rtn;
  pthread_t        sig_tid;
  pthread_t        disc_tid;
  char             *cmd;
  struct sigaction sa;

  if ((cmd = strrchr(argv[0], '/')) == NULL) {
    cmd = argv[0];
  } else {
    cmd++;
  }

  /* Daemonize */
  daemonize(cmd);

  /* Ensure we're the only daemon running */
  cl_debug("Checking for single instance");
  if (already_running()) {
    syslog(LOG_ERR, "daemon already running");
    exit(1);
  }

  /* Block all signals and setup handler */
  cl_debug("Setting up signal handlers");
  sa.sa_handler = SIG_DFL;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  if (sigaction(SIGHUP, &sa, NULL) < 0) {
    err_quit("%s: can't restore SIGHUP default", cmd);
  }
  sigfillset(&mask);
  if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0) {
    err_quit("SIG_BLOCK error");
  }

  /* Create a thread to handle signals */
  cl_debug("Creating signal handling thread");
  err = pthread_create(&sig_tid, NULL, sig_handler, 0);
  if (err != 0) {
    err_quit("can't create signal thread!");
  }

  cl_debug("clacksidd: Done with main setup, continuing");
  update_uuid_pool();
  rtn = listen_on_dom_socket(CL_ID_DOM_SOCKET);

  exit(0);
}
Ejemplo n.º 14
0
int kill_daemon(const char *pidfile)
{
	int pid = already_running(pidfile);

	if (pid) {
		printf("Signalling process with pid %d\n", pid);
		kill(pid, SIGTERM);
		sleep(1);
		kill(pid, SIGKILL);
	}
	else
		puts("No daemon running");

	return 0;
}
Ejemplo n.º 15
0
/*
 * Usage: ./judged oj_home [debug]
 */
int main(int argc, char *argv[])
{
	DEBUG = (argc > 2);
	//如果第2个参数指定了家目录,就设置为那个目录
	//在debug时有用
	//否则默认为/home/judge
	if (argc > 1) {
		strcpy(oj_home, argv[1]);
	} else {
		strcpy(oj_home, "/home/judge");
	}

	chdir(oj_home);		// change the dir

	//不调试就设为守护进程
	if (!DEBUG) {
		daemon_init();
	}

	//进程已经运行了
	if (strcmp(oj_home, "/home/judge") == 0 && already_running()) {
		write_log("This daemon program is already running.\n");
		exit(EXIT_FAILURE);
	}

	init_mysql_conf();	// set the database info

	//设置信号的回调函数
	signal(SIGQUIT, call_for_exit);
	signal(SIGKILL, call_for_exit);
	signal(SIGTERM, call_for_exit);

	int j = 1;
	while (1) {		// start to run
		//从数据库中查询出来的没有判的题目判完
		//然后一直询问
		while (j && !init_mysql()) {
			j = work();
		}
		write_log("next query after %d seconds.\n", sleep_time);
		sleep(sleep_time);
		j = 1;
	}

	return 0;
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
    int err;
    pthread_t tid;
    char *cmd;
    struct sigaction sa;

    if ((cmd = strrchr(argv[0],"/")) == NULL)
    {
        cmd = argv[0];
    }
    else
    {
        cmd++;
    }

    daemonize(cmd);

    if (already_running())
    {
        syslog(LOG_ERR,"daemon already running");
        exit(1);
    }

    sa.sa_handler = SIG_DFL;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL)<0)
    {
        err_quit("%s: can't restore SIGHUP default");
    }
    sigfillset(&mask);
    if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL))!=0)
    {
        err_exit(err, "SIG_BLOCK error");
    }

    err = pthread_create(&tid, NULL, thr_fn, 0);
    if (err!=0)
    {
        err_exit(err,"can't create thread");
    }

    exit(0);
}
Ejemplo n.º 17
0
static void inline stop_jacques(void)
{
    gint running = already_running();
    if (running == 0) {
        g_printf(_("jacques is not running!!!\n"));
        exit(0);
    } else if (running < 0) {
        g_printf(_("Unable to get jacques process id:%s\n"),
                 strerror(errno));
        exit(0);
    }
    if (kill(running, SIGINT)) {
        g_printf(_("Fail to send signal SIGINT to process %d:%s\n"),
                 running, strerror(errno));
    } else {
        g_printf(("Send signal SIGINT to jacques: %d\n"), running);
    }
    exit(EXIT_MASTER_OK);
}
Ejemplo n.º 18
0
Archivo: launch.c Proyecto: aufau/xqf
int client_launch (const struct condef *con, int forkit) {

	if (!con || !con->server || !con->s)
		return FALSE;

	if (already_running (con->s->type))
		return FALSE;

	if (games[con->s->type].write_config) {
		if (!(*games[con->s->type].write_config) (con))
			return FALSE;
	}

	if (games[con->s->type].exec_client) {
		if ( (*games[con->s->type].exec_client) (con, forkit) < 0)
			return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 19
0
static inline JaConfig *initialize_jacques(void)
{
    JaConfig *cfg = read_config();
    g_mkdir_with_parents(CONFIG_RUNTIME_LOCATION, 0755);
    g_mkdir_with_parents(CONFIG_LOG_LOCATION, 0755);
    g_mkdir_with_parents(CONFIG_LOG_LOCATION, 0755);
    gint running = already_running();
    if (running > 0) {
        g_printf(_("jacqueas is already running!!!\n"));
        exit(EXIT_MASTER_ALREADY_RUNNING);
    } else if (running < 0) {
        g_printf(_("Unable to create pid file:%s\n"), strerror(errno));
        exit(EXIT_MASTER_INITIALIZE);
    } else if (!daemonize() || !initialize_default_log()
               || !lock_pidfile()) {
        g_printf(_("Unable to initialize jacques:%s\n"), strerror(errno));
        exit(EXIT_MASTER_INITIALIZE);
    }
    return cfg;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
	int err;
	pthread_t tid;
	struct sigaction sa;
	char *cmd;

	if(NULL == (cmd = strrchr(argv[0], '/')))
		cmd = argv[0];
	else
		cmd ++;
	syslog(LOG_ERR, "main thread id is %u.\n", (unsigned)pthread_self());

//	daemonize(cmd);
	daemon(0, 0);
	if(already_running())
	{
		syslog(LOG_ERR, "xdaemon already running.\n");
		exit(1);
	}
	syslog(LOG_ERR, "main thread 2 id is %u.\n", (unsigned)pthread_self());

//	/*
	sa.sa_handler = SIG_DFL;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if(sigaction(SIGHUP, &sa, NULL) < 0)
		log_quit("can't restore SIGHUP default");
	sigfillset(&mask);
	if((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
			log_exit(err, "SIG_BLOCK error");

	err = pthread_create(&tid, NULL, thread_func, 0);
	if(err != 0)
		log_exit(err, "can't create thread");

//*/
	test_func();

	exit(0);
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
	char				*cmd;
	struct sigaction	sa;
	if((cmd=strrchr(argv[0],'/'))==NULL)
		cmd=argv[0];
	else
		cmd++;
	
	//became a daemon
	daemonize(cmd);
	
	//make sure only one copy of the daemon is running
	if(already_running()){
		syslog(LOG_ERR,"daemon already running");
		exit(1);
	}

	//handle signals of interest.
	sa.sa_handler = sigterm;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask,SIGHUP);
	sa.sa_flags=0;
	if(sigaction(SIGTERM,&sa,NULL)<0){
		syslog(LOG_ERR,"can't catch SIGTERM: %s",strerror(errno));
		exit(1);
	}
	sa.sa_handler=sighup;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask,SIGTERM);
	sa.sa_flags=0;
	if(sigaction(SIGHUP,&sa,NULL)<0){
		syslog(LOG_ERR,"can't catch SIGHUP: %s",strerror(errno));
		exit(1);
	}


	//Proceed with the rest of the daemon

	exit(0);
}
Ejemplo n.º 22
0
int main(int argc, char  **argv)
{	
	out_bgorlit();
	test_hex2pro();
	test_pro2hex();
	
	cmd_parser(argc,argv,&glb_cfg);
	if(glb_cfg.daemon)
		run_as_daemon();
	
	/*
	 * Make sure only one copy of the daemon is running.
	 */
	if (already_running()) {
		debug(LOG_ERR, "daemon already running\n");
		exit(1);
	}
	
	pthread_mutex_init(&(glb_cfg.lock), NULL);
	pthread_cond_init(&(glb_cfg.cond), NULL);
//	init_log(argv[0]);
	
	init_signals();
	alarm(WT_SDCARD_PRIOD);

	pthread_t sorpid;
	pthread_create(&sorpid,NULL,handle_uart,NULL);
	
	pthread_t cmdpid;
	pthread_create(&cmdpid,NULL,handle_socket_machine,NULL);

	
	pthread_join(sorpid,NULL);
	pthread_join(cmdpid,NULL);
	
	debug(LOG_NOTICE,"<==========Process exit!\n");
//	close_log();
	return 0;
}
Ejemplo n.º 23
0
int
main(int argc, char *argv[])
{
	char				*cmd;
	struct	sigaction	sa;

	if ((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else
		cmd++;

	daemonize(cmd);

	if (already_running()) {
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}

	sa.sa_handler = sigterm;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGHUP);
	sa.sa_flags = 0;
	if (sigaction(SIGTERM, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGTERM: %s", strerror(errno));
		exit(1);
	}
	sa.sa_handler = sighup;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGTERM);
	sa.sa_flags = 0;
	if (sigaction(SIGHUP, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGHUP: %s", strerror(errno));
		exit(1);
	}

	exit(0);
}
Ejemplo n.º 24
0
int
main(int argc ,char **argv)
{
    char *cmd;
    struct sigaction sa;

    if ((cmd = strrchr(argv[0],"/")) == NULL) 
        cmd = argv[0];
    else 
        cmd++;

    daemonize(cmd);

    if (already_running()) {
        syslog(LOG_INFO,"daemon already running");
        exit(1);
    }

    sa.sa_handler = sigterm;
    sigemptyset(&sa.sa_mask);
    sa.sa_flag = 0;
    if (sigactioin(SIGTERM,&sa,NULL) < 0) 
        pirntf("%s:can't restore SIGTERM default\n");

    sa.sa_handler = sighup;
    sigemptyset(&sa.sa_mask);
    sa.sa_flag = 0;
    if (sigactioin(SIGHUP,&sa,NULL) < 0) 
        pirntf("%s:can't restore SIGHUP default\n");

    /*
     * Proceed with the reset of the daemon.
     * 
     */

    return 0;
}
Ejemplo n.º 25
0
int daemonize(void) {

	umask(0);

	pid_t pid;
	pid = fork();

	if (pid < 0) {
		return -1;
	}

	/* Ensure that we're not a process group leader,
	 * so that it's safe to create a new session
	 */
	if (pid != 0) {
		exit(0);
	}

	setsid();

	/* Close every open file descriptor */
	struct rlimit rlim;
	int max_fd;
	if (getrlimit(RLIMIT_NOFILE, &rlim) < 0 || rlim.rlim_cur == RLIM_INFINITY) {
		max_fd = 1024;
	} else {
		max_fd = rlim.rlim_cur;
	}

	int i;
	for (i = 0; i < max_fd; i++) {
		close(i);
	}

	/* chdir to root, or to a specified, known location where the daemon
	 * will do its work
	 */
	chdir("/");

	/* Prepare error / message logging */
	openlog(DAEMON_NAME, 0, 0);

	/* Ensure that we're not a session leader to prevent controlling terminal allocation
	 * This is recommended on System V based systems, but not really needed on other UNIX
	 * flavors
	 */
	pid = fork();
	if (pid < 0) {
		syslog(LOG_ERR, "Couldn't fork() after creating a new session.\n");
		exit(EXIT_FAILURE);
	}
	if (pid != 0) {
		exit(0);
	}

	/* Some library functions and system utilities expect to have stdin, stdout and stderr
	 * opened */
	int sink = open("/dev/null", O_RDWR, 0);
	dup2(sink, STDIN_FILENO);

	if (sink != STDIN_FILENO) {
		close(sink);
	}

	dup2(STDIN_FILENO, STDOUT_FILENO);
	dup2(STDIN_FILENO, STDERR_FILENO);

	/* Catch SIGHUP. SIGHUP on daemons is typically used to force the daemon to reread its
	 * configuration file.
	 * Why SIGHUP? Because SIGHUP is the signal sent by the terminal driver to the controlling
	 * process in a session when the terminal driver detects a network disconnect or a modem
	 * hangup (hence "HUP").
	 * Since daemons do not have a controlling terminal, SIGHUP can't possibly be triggered
	 * by a terminal disconnect. Thus, people have historically used it with a different meaning
	 * in daemons
	 */

	struct sigaction sighandler;
	sighandler.sa_handler = sighup_handler;
	sighandler.sa_flags = 0;
	sigemptyset(&sighandler.sa_mask);

	if (sigaction(SIGHUP, &sighandler, NULL) < 0) {
		syslog(LOG_ERR, "Couldn't catch SIGHUP.\n");
		exit(EXIT_FAILURE);
	}

	sighandler.sa_handler = terminate_handler;
	if (sigaction(SIGINT, &sighandler, NULL) < 0) {
		syslog(LOG_ERR, "Couldn't catch SIGINT.\n");
		exit(EXIT_FAILURE);
	}

	if (sigaction(SIGTERM, &sighandler, NULL) < 0) {
		syslog(LOG_ERR, "Couldn't catch SIGTERM.\n");
		exit(EXIT_FAILURE);
	}

	int running = already_running();
	if (running == -1) {
		syslog(LOG_INFO, "already_running() error: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	} else if (running == 1) {
		syslog(LOG_INFO, "Daemon is already running. See " LOCKFILE "\n");
		exit(EXIT_SUCCESS);
	}

	syslog(LOG_INFO, "daemonize() complete. PID = %ld\n", (long) getpid());
	syslog(LOG_INFO, "Send SIGTERM or SIGINT to terminate\n");

	return 0;
}
Ejemplo n.º 26
0
/*
 * runas is the pseudo-user identity we assume
 * jail is the directory we chdir() to before doing chroot(".")
 * pidfile is written outside the jail.
 * flags is a bitflag option specifier
 */
int daemonize(const char *runas, const char *jail, const char *pidfile, int flags)
{
	struct passwd *pw;
	int pid = already_running(pidfile);

	daemon_pidfile = strdup(pidfile);

	if (pid > 0) {
		fprintf(stderr, "Another Merlin instance is already running with pid %d\n", pid);
		exit(EXIT_FAILURE);
	}

	/* don't drop privs or chdir if we're debugging */
	if (flags & DMNZ_NOFORK)
		return write_pid(pidfile, getpid());

	if (jail && chdir(jail) < 0) {
		fprintf(stderr, "Failed to chdir() to '%s': %s\n", jail, strerror(errno));
		return -1;
	}

	pid = fork();
	if (pid < 0) {
		fprintf(stderr, "fork() failed: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (!pid) {
		/* baby daemon goes here */

		/* start a new process group */
		setsid();

		if (jail && flags & DMNZ_CHROOT && chroot(".") < 0) {
			fprintf(stderr, "chroot(%s) failed: %s", jail, strerror(errno));
			exit(EXIT_FAILURE);
		}

		pw = get_user_entry(runas);
		if (pw && drop_privs(pw) != pw->pw_uid) {
			fprintf(stderr, "Failed to drop privileges to user %s", pw->pw_name);
			exit(EXIT_FAILURE);
		}
		free(pw);

		return 0;
	}

	if (write_pid(pidfile, pid) != pid) {
		fprintf(stderr, "Failed to write pidfile '%s': %s\n",
				pidfile, strerror(errno));

		kill(pid, SIGTERM);
		kill(pid, SIGKILL);
		exit(EXIT_FAILURE);
	}

	if (flags & DMNZ_NOFORK)
		return pid;

	_exit(EXIT_SUCCESS);
	return 0;
}
Ejemplo n.º 27
0
int main (int argc, char *argv[]) {
	char *cmd;
	struct sigaction sa;
	int fifofd;
	long int pidslave[3];
//	char fifoslave[512];
	struct harvester *sh;
	pthread_t *ht;
	pthread_attr_t ha;
	GError *error = NULL;
	GOptionContext *context;
	static int use_daemonize = 1;
	static GOptionEntry entries[] = {
		{"disable-daemonize", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &use_daemonize, "do not daemonize", NULL},
		{NULL}
	};


	context = g_option_context_new ("launch seed harvester");
	g_option_context_add_main_entries (context, entries, NULL);
	g_option_context_set_summary(context, "xmimsim-harvester: a daemon that gathers seeds from /dev/random...");
	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		g_print ("option parsing failed: %s\n", error->message);
		exit (1);
	}

	if ((cmd = strrchr(argv[0], '/')) == NULL)
		cmd = argv[0];
	else
		cmd++;

	if (use_daemonize)
		daemonize(cmd);
	else {
		openlog(cmd, LOG_CONS | LOG_PID, LOG_DAEMON);
		setlogmask(LOG_UPTO(LOG_DEBUG));
	}

	if (already_running()) {
		syslog(LOG_ERR, "daemon already running");
		exit(1);
	}

	sa.sa_handler = sigterm;
	sigfillset(&sa.sa_mask);
	//sigaddset(&sa.sa_mask, SIGTERM);
	sa.sa_flags=0;
	if (sigaction(SIGTERM, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGTERM: %s", strerror(errno));
		exit(1);
	}
	if (sigaction(SIGSEGV, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGSEGV: %s", strerror(errno));
		exit(1);
	}
	if (sigaction(SIGBUS, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGBUS: %s", strerror(errno));
		exit(1);
	}
	if (sigaction(SIGILL, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGILL: %s", strerror(errno));
		exit(1);
	}
	if (sigaction(SIGQUIT, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGQUIT: %s", strerror(errno));
		exit(1);
	}

	sa.sa_handler = sighup;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGHUP);
	sa.sa_flags=0;
	if (sigaction(SIGHUP, &sa, NULL) < 0) {
		syslog(LOG_ERR, "can't catch SIGHUP: %s", strerror(errno));
		exit(1);
	}


	if (xmi_start_random_acquisition_dev() != 1) {
		syslog(LOG_ERR,"xmi_start_random_acquisition_dev error");
		exit(1);
	}


	syslog(LOG_INFO,"daemon running succesfully");

	pthread_attr_init(&ha);
	pthread_attr_setdetachstate(&ha,PTHREAD_CREATE_DETACHED);


	while (1) {
		//create fifo
		if (mkfifo(FIFOMASTER, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == -1) {
			syslog(LOG_ERR,"Could not create named link" FIFOMASTER ": %s",strerror(errno));
			exit(1);
		}
		if ((fifofd = open(FIFOMASTER,O_RDONLY)) == -1) {
			syslog(LOG_ERR,"Could not open named link" FIFOMASTER ": %s",strerror(errno));
			exit(1);
		}

		//read pid from slave
		if (read(fifofd,pidslave,3*sizeof(long int)) != 3*sizeof(long int)) {
			syslog(LOG_ERR,"Error reading from " FIFOMASTER ": %s",strerror(errno));
			exit(1);
		}
		close(fifofd);
		unlink(FIFOMASTER);
#ifdef DEBUG
		syslog(LOG_INFO,"Daemon -> pid: %li  counter: %li number: %li",pidslave[0],pidslave[1],pidslave[2]);
#endif
		//allocate necessary variables
		sh = (struct harvester *) g_malloc(sizeof(struct harvester));
		ht = (pthread_t *) g_malloc(sizeof(pthread_t));

		//create slave fifo
		sh->fifoslave = g_strdup_printf(FIFOSLAVE "%li.%li",pidslave[0],pidslave[1]);
		sh->nseeds = pidslave[2];

		//start thread
		pthread_create(ht,&ha,harvest_thread,sh);




	}


	return 0;
}
int main(int argc, char *argv[])
{
     int                err = 0;
     pthread_t          tid ;
     char               *cmd = NULL;
     struct sigaction   sa;

     if ((cmd = strrchr(argv[0], '/')) == NULL)
     {
          cmd = argv[0];
     }
     else
     {
         cmd++;
     }

     syslog(LOG_ERR, "before daemonize !!!!!!!!!!!!!!!!!!");
     //变为守护进程
     daemonize(cmd);


     //确保只有一个守护进程副本在运行
     if (already_running())
     {
          syslog(LOG_ERR, "daemon alread running");
          exit(1);
     }

     //restore SIGHUP default and block all signal
     sa.sa_handler = SIG_DFL;       //???
     sigemptyset(&sa.sa_mask);
     sa.sa_flags = 0;               //???

     if (sigaction(SIGHUP, &sa, NULL) < 0)
     {
          err_quit("%s: can't restore SIGHUP default");
     }

     sigfillset(&mask);     // 把所有信号都放到mask集合里面

     //把mask信号集里的信号添加到线程的信号屏蔽集里面
     if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
     {
          err_exit(err, "SIG_BLOCK error");
     }

     //新建一个线程处理SIGHUP 和SIGTERM
     syslog(LOG_ERR, "before pthread_create");
     err = pthread_create(&tid, NULL, thr_fn, 0);
     if (err != 0)
     {
          err_exit(err, "can't create thread");
     }

     //kill 自定义
     kill(getpid(), SIGHUP);
     sleep(1);
     //proceed with the rest of the daemon
     //

     exit(0);
}
Ejemplo n.º 29
0
int
main(int argc, char *argv[]) {
    int rc;
    uv_loop_t *loop;

    parse_opts(argc, argv);

#if !defined(_WIN32)
    if (xsignal) {
        return signal_process(xsignal, pidfile);
    }
#endif

    if (!password || !server_addr_buf) {
        print_usage(argv[0]);
        return 1;
    }

    init();

#if !defined(_WIN32)
    if (daemon_mode) {
        if (daemonize()) {
            return 1;
        }
        if (already_running(pidfile)) {
            logger_stderr("xsocks already running.");
            return 1;
        }
    }
#endif

    loop = uv_default_loop();

    rc = resolve_addr(local_addr, &bind_addr);
    if (rc) {
        logger_stderr("invalid local address");
        return 1;
    }

    rc = resolve_addr(server_addr_buf, &server_addr);
    if (rc) {
        logger_stderr("invalid server address");
        return 1;
    }

    udprelay_init();

    if (concurrency <= 1) {
        struct server_context ctx;
        ctx.udprelay = 1;
        ctx.udp_fd = create_socket(SOCK_DGRAM, 0);
        ctx.local_addr = &bind_addr;
        ctx.server_addr = &server_addr;

        uv_tcp_init(loop, &ctx.tcp);
        rc = uv_tcp_bind(&ctx.tcp, &bind_addr, 0);
        if (rc) {
            logger_stderr("bind error: %s", uv_strerror(rc));
            return 1;
        }
        rc = uv_listen((uv_stream_t*)&ctx.tcp, 128, client_accept_cb);
        if (rc == 0) {
            logger_log(LOG_INFO, "listening on %s", local_addr);

#if !defined(_WIN32)
            setup_signal(loop, signal_cb, &ctx);
#endif

            udprelay_start(loop, &ctx);

            uv_run(loop, UV_RUN_DEFAULT);

            close_loop(loop);

        } else {
            logger_stderr("listen error: %s", uv_strerror(rc));
        }

    } else {
#if !defined(_WIN32)
        struct server_context *servers = calloc(concurrency, sizeof(servers[0]));
        for (int i = 0; i < concurrency; i++) {
            struct server_context *ctx = servers + i;
            ctx->index = i;
            ctx->tcp_fd = create_socket(SOCK_STREAM, 1);
            ctx->udp_fd = create_socket(SOCK_DGRAM, 1);
            ctx->udprelay = 1;
            ctx->accept_cb = client_accept_cb;
            ctx->local_addr = &bind_addr;
            ctx->server_addr = &server_addr;
            rc = uv_sem_init(&ctx->semaphore, 0);
            rc = uv_thread_create(&ctx->thread_id, consumer_start, ctx);
        }

        logger_log(LOG_INFO, "listening on %s", local_addr);

        setup_signal(loop, signal_cb, servers);

        uv_run(loop, UV_RUN_DEFAULT);

        close_loop(loop);

        for (int i = 0; i < concurrency; i++) {
            uv_sem_wait(&servers[i].semaphore);
        }
        free(servers);
#else
        logger_stderr("don't support multithreading.");
        return 1;
#endif
	}

    udprelay_destroy();

#if !defined(_WIN32)
    if (daemon_mode) {
        delete_pidfile(pidfile);
    }
#endif

    logger_exit();

    return 0;
}
Ejemplo n.º 30
0
int
main(int argc, char *argv[]) {
    int rc;
    uv_loop_t *loop;
    struct sockaddr bind_addr;

    parse_opts(argc, argv);

    if (xsignal) {
        return signal_process(xsignal, pidfile);
    }

    if (!tunnel_mode || !dest_addr || !password) {
        print_usage(argv[0]);
        return 1;
    }

    if (init()) {
        return 1;
    }

    if (daemon_mode) {
        if (daemonize()) {
            return 1;
        }
        if (already_running(pidfile)) {
            logger_stderr("xtunnel already running.");
            return 1;
        }
    }

    loop = uv_default_loop();

    rc = resolve_addr(source_addr, &bind_addr);
    if (rc) {
        logger_stderr("invalid local address");
        return 1;
    }

    rc = resolve_addr(dest_addr, &target_addr);
    if (rc) {
        logger_stderr("invalid target address");
        return 1;
    }

    if (concurrency <= 1) {
        struct server_context ctx;
        uv_tcp_init(loop, &ctx.tcp);
        rc = uv_tcp_bind(&ctx.tcp, &bind_addr, 0);
        if (rc) {
            logger_stderr("bind error: %s", uv_strerror(rc));
            return 1;
        }
        rc = uv_listen((uv_stream_t*)&ctx.tcp, SOMAXCONN, source_accept_cb);
        if (rc == 0) {
            logger_log(LOG_INFO, "listening on %s", source_addr);

            setup_signal(loop, signal_cb, &ctx);

            uv_run(loop, UV_RUN_DEFAULT);

            close_loop(loop);

        } else {
            logger_stderr("listen error: %s", uv_strerror(rc));
        }

    } else {
        struct server_context *servers = calloc(concurrency, sizeof(servers[0]));
        for (int i = 0; i < concurrency; i++) {
            struct server_context *ctx = servers + i;
            ctx->index = i;
            ctx->tcp_fd = create_socket(SOCK_STREAM, 1);
            ctx->accept_cb = source_accept_cb;
            ctx->nameserver_num = -1;
            ctx->local_addr = &bind_addr;
            rc = uv_sem_init(&ctx->semaphore, 0);
            rc = uv_thread_create(&ctx->thread_id, consumer_start, ctx);
        }

        logger_log(LOG_INFO, "listening on %s", source_addr);

        setup_signal(loop, signal_cb, servers);

        uv_run(loop, UV_RUN_DEFAULT);

        close_loop(loop);

        for (int i = 0; i < concurrency; i++) {
            uv_sem_wait(&servers[i].semaphore);
        }
        free(servers);
    }

    if (daemon_mode) {
        delete_pidfile(pidfile);
    }

    return 0;
}