当前位置: 首页>>代码示例>>C++>>正文


C++ daemonize函数代码示例

本文整理汇总了C++中daemonize函数的典型用法代码示例。如果您正苦于以下问题:C++ daemonize函数的具体用法?C++ daemonize怎么用?C++ daemonize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了daemonize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: rtasd

static int rtasd(void *unused)
{
	unsigned int err_type;
	int cpu = 0;
	int event_scan = rtas_token("event-scan");
	cpumask_t all = CPU_MASK_ALL;
	int rc;

	daemonize("rtasd");

	if (event_scan == RTAS_UNKNOWN_SERVICE || get_eventscan_parms() == -1)
		goto error;

	rtas_log_buf = vmalloc(rtas_error_log_buffer_max*LOG_NUMBER);
	if (!rtas_log_buf) {
		printk(KERN_ERR "rtasd: no memory\n");
		goto error;
	}

	/* We can use rtas_log_buf now */
	no_more_logging = 0;

	printk(KERN_ERR "RTAS daemon started\n");

	DEBUG("will sleep for %d jiffies\n", (HZ*60/rtas_event_scan_rate) / 2);

	/* See if we have any error stored in NVRAM */
	memset(logdata, 0, rtas_error_log_max);

	rc = nvram_read_error_log(logdata, rtas_error_log_max, &err_type);
	if (!rc) {
		if (err_type != ERR_FLAG_ALREADY_LOGGED) {
			pSeries_log_error(logdata, err_type | ERR_FLAG_BOOT, 0);
		}
	}

	/* First pass. */
	lock_cpu_hotplug();
	for_each_online_cpu(cpu) {
		DEBUG("scheduling on %d\n", cpu);
		set_cpus_allowed(current, cpumask_of_cpu(cpu));
		DEBUG("watchdog scheduled on cpu %d\n", smp_processor_id());

		do_event_scan(event_scan);
		set_current_state(TASK_INTERRUPTIBLE);
		schedule_timeout(HZ);
	}
	unlock_cpu_hotplug();

	if (surveillance_timeout != -1) {
		DEBUG("enabling surveillance\n");
		enable_surveillance(surveillance_timeout);
		DEBUG("surveillance enabled\n");
	}

	lock_cpu_hotplug();
	cpu = first_cpu_const(mk_cpumask_const(cpu_online_map));
	for (;;) {
		set_cpus_allowed(current, cpumask_of_cpu(cpu));
		do_event_scan(event_scan);
		set_cpus_allowed(current, all);

		/* Drop hotplug lock, and sleep for a bit (at least
		 * one second since some machines have problems if we
		 * call event-scan too quickly). */
		unlock_cpu_hotplug();
		set_current_state(TASK_INTERRUPTIBLE);
		schedule_timeout((HZ*60/rtas_event_scan_rate) / 2);
		lock_cpu_hotplug();

		cpu = next_cpu_const(cpu, mk_cpumask_const(cpu_online_map));
		if (cpu == NR_CPUS)
			cpu = first_cpu_const(mk_cpumask_const(cpu_online_map));
	}

error:
	/* Should delete proc entries */
	return -EINVAL;
}
开发者ID:iPodLinux,项目名称:linux-2.6.7-ipod,代码行数:79,代码来源:rtasd.c

示例2: nfsd

/*
 * This is the NFS server kernel thread
 */
static void
nfsd(struct svc_rqst *rqstp)
{
	struct svc_serv	*serv = rqstp->rq_server;
	struct fs_struct *fsp;
	int		err;
	struct nfsd_list me;
	sigset_t shutdown_mask, allowed_mask;

	/* Lock module and set up kernel thread */
	lock_kernel();
	daemonize("nfsd");
	current->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;

	/* After daemonize() this kernel thread shares current->fs
	 * with the init process. We need to create files with a
	 * umask of 0 instead of init's umask. */
	fsp = copy_fs_struct(current->fs);
	if (!fsp) {
		printk("Unable to start nfsd thread: out of memory\n");
		goto out;
	}
	exit_fs(current);
	current->fs = fsp;
	current->fs->umask = 0;

	siginitsetinv(&shutdown_mask, SHUTDOWN_SIGS);
	siginitsetinv(&allowed_mask, ALLOWED_SIGS);

	nfsdstats.th_cnt++;

	lockd_up();				/* start lockd */

	me.task = current;
	list_add(&me.list, &nfsd_list);

	unlock_kernel();

	/*
	 * We want less throttling in balance_dirty_pages() so that nfs to
	 * localhost doesn't cause nfsd to lock up due to all the client's
	 * dirty pages.
	 */
	current->flags |= PF_LESS_THROTTLE;

	/*
	 * The main request loop
	 */
	for (;;) {
		/* Block all but the shutdown signals */
		sigprocmask(SIG_SETMASK, &shutdown_mask, NULL);

		/*
		 * Find a socket with data available and call its
		 * recvfrom routine.
		 */
		while ((err = svc_recv(serv, rqstp,
				       60*60*HZ)) == -EAGAIN)
			;
		if (err < 0)
			break;
		update_thread_usage(atomic_read(&nfsd_busy));
		atomic_inc(&nfsd_busy);

		/* Lock the export hash tables for reading. */
		exp_readlock();

		/* Process request with signals blocked.  */
		sigprocmask(SIG_SETMASK, &allowed_mask, NULL);

		svc_process(serv, rqstp);

		/* Unlock export hash tables */
		exp_readunlock();
		update_thread_usage(atomic_read(&nfsd_busy));
		atomic_dec(&nfsd_busy);
	}

	if (err != -EINTR) {
		printk(KERN_WARNING "nfsd: terminating on error %d\n", -err);
	} else {
		unsigned int	signo;

		for (signo = 1; signo <= _NSIG; signo++)
			if (sigismember(&current->pending.signal, signo) &&
			    !sigismember(&current->blocked, signo))
				break;
		err = signo;
	}

	lock_kernel();

	/* Release lockd */
	lockd_down();

	/* Check if this is last thread */
	if (serv->sv_nrthreads==1) {
//.........这里部分代码省略.........
开发者ID:FelipeFernandes1988,项目名称:Alice-1121-Modem,代码行数:101,代码来源:nfssvc.c

示例3: set_details


//.........这里部分代码省略.........
    if (clt_settings.par_connections <= 0) {
        clt_settings.par_connections = 1;
    } else if (clt_settings.par_connections > MAX_CONNECTION_NUM) {
        clt_settings.par_connections = MAX_CONNECTION_NUM;
    }
    tc_log_info(LOG_NOTICE, 0, "parallel connections per target:%d",
            clt_settings.par_connections);

    if(isOfflineMode())
    {
      if (clt_settings.pcap_file == NULL) {
          tc_log_info(LOG_ERR, 0, "it must have -i argument for offline");
          fprintf(stderr, "no -i argument\n");
          return -1;
      }
  
      if (clt_settings.accelerated_times < 1) {
          clt_settings.accelerated_times = 1;
      }
  
      tc_log_info(LOG_NOTICE, 0, "accelerated %d times,interval:%llu ms",
              clt_settings.accelerated_times, clt_settings.interval);
  
      if (clt_settings.interval > 0) {
          clt_settings.interval = clt_settings.interval * 1000;
      }
    }
#if (TCPCOPY_PCAP_SEND)
    if (clt_settings.output_if_name != NULL) {
        tc_log_info(LOG_NOTICE, 0, "output device:%s", 
                clt_settings.output_if_name);
    } else {
        tc_log_info(LOG_ERR, 0, "output device is null");
        return -1;
    }
#endif

#if (TCPCOPY_PCAP)
    if (clt_settings.raw_device != NULL) {
        tc_log_info(LOG_NOTICE, 0, "device:%s", clt_settings.raw_device);
        if (strcmp(clt_settings.raw_device, DEFAULT_DEVICE) == 0) {
            clt_settings.raw_device = NULL; 
        } else {
            retrieve_devices(clt_settings.raw_device, &(clt_settings.devices));
        }
    }

    if (clt_settings.user_filter != NULL) {
        tc_log_info(LOG_NOTICE, 0, "user filter:%s", clt_settings.user_filter);
        len = strlen(clt_settings.user_filter);
        if (len >= MAX_FILTER_LENGH) {
            tc_log_info(LOG_ERR, 0, "user filter is too long");
            return -1;
        }
        memcpy(clt_settings.filter, clt_settings.user_filter, len);

    } else {
        extract_filter();
    }
#endif

#if (TCPCOPY_MYSQL_ADVANCED)
    if (clt_settings.user_pwd != NULL) {
        tc_log_info(LOG_NOTICE, 0, "-u argument:%s",clt_settings.user_pwd);
        if (retrieve_mysql_user_pwd_info(clt_settings.user_pwd) == -1) {
            tc_log_info(LOG_ERR, 0, "wrong -u argument");
            return -1;
        }
    } else {
        tc_log_info(LOG_ERR, 0, "it must have -u argument");
        fprintf(stderr, "no -u argument\n");
        return -1;
    }
#endif

#if (TCPCOPY_DR)
    /* retrieve real server ip addresses  */
    if (clt_settings.raw_rs_list != NULL) {
        tc_log_info(LOG_NOTICE, 0, "s parameter:%s", 
                clt_settings.raw_rs_list);
        retrieve_real_servers();
    } else {
        tc_log_info(LOG_WARN, 0, "no real server ip addresses");
        return -1;
    }
#endif

    /* daemonize */
    if (clt_settings.do_daemonize) {
        if (sigignore(SIGHUP) == -1) {
            tc_log_info(LOG_ERR, errno, "Failed to ignore SIGHUP");
        }
        if (daemonize() == -1) {
            fprintf(stderr, "failed to daemonize() in order to daemonize\n");
            return -1;
        }    
    }    

    return 0;
}
开发者ID:microelec,项目名称:tcpcopy,代码行数:101,代码来源:main.c

示例4: MODULEMAINFUNC

int MODULEMAINFUNC (int argc, char** argv){

 SOCKET sock = INVALID_SOCKET;
 int i=0;
 SASIZETYPE size;
 pthread_t thread;
 struct clientparam defparam;
 int demon=0;
 struct clientparam * newparam;
 char *s;
 int error = 0;
 unsigned sleeptime;
 struct extparam myconf;
 unsigned char buf[256];
 struct pollfd fds;
 int opt = 1;
 PROXYFUNC pf;
 FILE *fp = NULL;
 int maxchild;
 int silent = 0;
 int nlog = 5000;
 char loghelp[] =
#ifdef STDMAIN
	" -d go to background (daemon)\n"
#endif
	" -fFORMAT logging format (see documentation)\n"
	" -l log to stderr\n"
	" -lFILENAME log to FILENAME\n"
	" -bBUFSIZE size of network buffer (default 4096 for TCP, 16384 for UDP)\n"
#ifndef _WIN32
	" [email protected] log to syslog IDENT\n"
#endif
	" -t be silenT (do not log service start/stop)\n"
	" -iIP ip address or internal interface (clients are expected to connect)\n"
	" -eIP ip address or external interface (outgoing connection will have this)\n";

 int childcount=0;
 pthread_mutex_t counter_mutex;


#ifdef _WIN32
 unsigned long ul;
#endif
#ifndef UDP
 int new_sock = INVALID_SOCKET;
 struct linger lg;
#endif
#ifdef _WIN32
 HANDLE h;
#endif
#ifdef STDMAIN
#ifdef _WIN32
 WSADATA wd;
 WSAStartup(MAKEWORD( 1, 1 ), &wd);
#else
 signal(SIGPIPE, SIG_IGN);

 pthread_attr_init(&pa);
 pthread_attr_setstacksize(&pa,PTHREAD_STACK_MIN + 16384);
 pthread_attr_setdetachstate(&pa,PTHREAD_CREATE_DETACHED);
#endif
#endif


 pf = childdef.pf;
 memcpy(&myconf, &conf, sizeof(myconf));
 memset(&defparam, 0, sizeof(struct clientparam));
 defparam.version = paused;
 defparam.childcount = &childcount;
 defparam.logfunc = myconf.logfunc;
 defparam.authfunc = myconf.authfunc;
 defparam.aclnum = myconf.aclnum;
 defparam.service = childdef.service;
 defparam.usentlm = 1;
 defparam.stdlog = NULL;
 defparam.time_start = time(NULL);
 maxchild = myconf.maxchild;

#ifndef STDMAIN
 if(!conf.services){
	conf.services = &defparam;
 }
 else {
	defparam.next = conf.services;
	conf.services = conf.services->prev = &defparam;
 }
#endif

 pthread_mutex_init(defparam.counter_mutex = &counter_mutex, NULL);

 for (i=1; i<argc; i++) {
	if(*argv[i]=='-') {
		switch(argv[i][1]) {
		 case 'd': 
			if(!demon)daemonize();
			demon = 1;
			break;
		 case 'l':
			defparam.logfunc = logstdout;
			defparam.logtarget = (unsigned char*)mystrdup(argv[i]);
//.........这里部分代码省略.........
开发者ID:areiter,项目名称:InMemoryFuzzing,代码行数:101,代码来源:proxymain.c

示例5: main


//.........这里部分代码省略.........
				preferred_hostname = optarg;
				break;
			case 'o':
				debug_config_file(optarg);
				break;
			case 'O':
				debug_config_file_size(string_metric_parse(optarg));
				break;
			case 'p':
				port = atoi(optarg);
				break;
			case 'S':
				fork_mode = 0;
				break;
			case 'T':
				child_procs_timeout = string_time_parse(optarg);
				break;
			case 'u':
				list_push_head(outgoing_host_list, xxstrdup(optarg));
				break;
			case 'U':
				outgoing_timeout = string_time_parse(optarg);
				break;
			case 'v':
				cctools_version_print(stdout, argv[0]);
				return 0;
			case 'Z':
				port_file = optarg;
				port = 0;
				break;
			}
	}

	if (is_daemon) daemonize(0, pidfile);

	cctools_version_debug(D_DEBUG, argv[0]);

	if(logfilename) {
		logfile = fopen(logfilename,"a");
		if(!logfile) fatal("couldn't open %s: %s\n",optarg,strerror(errno));
	}

	current = time(0);
	debug(D_NOTICE, "*** %s starting at %s", argv[0], ctime(&current));

	if(!list_size(outgoing_host_list)) {
		list_push_head(outgoing_host_list, CATALOG_HOST_DEFAULT);
	}

	install_handler(SIGPIPE, ignore_signal);
	install_handler(SIGHUP, ignore_signal);
	install_handler(SIGCHLD, ignore_signal);
	install_handler(SIGINT, shutdown_clean);
	install_handler(SIGTERM, shutdown_clean);
	install_handler(SIGQUIT, shutdown_clean);
	install_handler(SIGALRM, shutdown_clean);

	if(!preferred_hostname) {
		domain_name_cache_guess(hostname);
		preferred_hostname = hostname;
	}

	username_get(owner);
	starttime = time(0);

	table = jx_database_create(history_dir);
开发者ID:btovar,项目名称:cctools,代码行数:67,代码来源:catalog_server.c

示例6: openvpn_plugin_open_v1


//.........这里部分代码省略.........
    {
      const int nv_len = string_array_len (argv) - base_parms;
      int i;

      if ((nv_len & 1) == 1 || (nv_len / 2) > N_NAME_VALUE)
	{
	  fprintf (stderr, "AUTH-PAM: bad name/value list length\n");
	  goto error;
	}

      name_value_list.len = nv_len / 2;
      for (i = 0; i < name_value_list.len; ++i)
	{
	  const int base = base_parms + i * 2;
	  name_value_list.data[i].name = argv[base];
	  name_value_list.data[i].value = argv[base+1];
	}
    }

  /*
   * Get verbosity level from environment
   */
  {
    const char *verb_string = get_env ("verb", envp);
    if (verb_string)
      context->verb = atoi (verb_string);
  }

  /*
   * Make a socket for foreground and background processes
   * to communicate.
   */
  if (socketpair (PF_UNIX, SOCK_DGRAM, 0, fd) == -1)
    {
      fprintf (stderr, "AUTH-PAM: socketpair call failed\n");
      goto error;
    }

  /*
   * Fork off the privileged process.  It will remain privileged
   * even after the foreground process drops its privileges.
   */
  pid = fork ();

  if (pid)
    {
      int status;

      /*
       * Foreground Process
       */

      context->background_pid = pid;

      /* close our copy of child's socket */
      close (fd[1]);

      /* don't let future subprocesses inherit child socket */
      if (fcntl (fd[0], F_SETFD, FD_CLOEXEC) < 0)
	fprintf (stderr, "AUTH-PAM: Set FD_CLOEXEC flag on socket file descriptor failed\n");

      /* wait for background child process to initialize */
      status = recv_control (fd[0]);
      if (status == RESPONSE_INIT_SUCCEEDED)
	{
	  context->foreground_fd = fd[0];
	  return (openvpn_plugin_handle_t) context;
	}
    }
  else
    {
      /*
       * Background Process
       */

      /* close all parent fds except our socket back to parent */
      close_fds_except (fd[1]);

      /* Ignore most signals (the parent will receive them) */
      set_signals ();

#ifdef DO_DAEMONIZE
      /* Daemonize if --daemon option is set. */
      daemonize (envp);
#endif

      /* execute the event loop */
      pam_server (fd[1], argv[1], context->verb, &name_value_list);

      close (fd[1]);

      exit (0);
      return 0; /* NOTREACHED */
    }

 error:
  if (context)
    free (context);
  return NULL;
}
开发者ID:ThomasHabets,项目名称:openvpn-debian,代码行数:101,代码来源:auth-pam.c

示例7: main


//.........这里部分代码省略.........
        {
            if (verbose)
            {
                LOGD("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
    }

    if ((start_port > 0 && end_port <= 0) || (start_port <= 0 && end_port > 0)) {
        printf("Both start_prot and end_port needs to be specified\n");
        usage();
        exit(EXIT_FAILURE);
    }

    if (server_port != NULL && start_port > 0) {
        printf("server port can't be set if you want to use a port range\n");
        usage();
        exit(EXIT_FAILURE);
    }

    if (server_num == 0 || (server_port == NULL && start_port <= 0) || password == NULL)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) timeout = "60";

    if (pid_flags)
    {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    signal(SIGABRT, SIG_IGN);

    // setup asyncns
    asyncns_t *asyncns;
    if (!(asyncns = asyncns_new(dns_thread_num)))
    {
        FATAL("asyncns failed");
    }

    // setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // inilitialize ev loop
    struct ev_loop *loop = EV_DEFAULT;

    // inilitialize listen context
    struct listen_ctx listen_ctx_list[server_num + 1];

    // bind to each interface
    while (server_num > 0)
    {
        int index = --server_num;
        const char* host = server_host[index];
        int success = 1;
        int listenfd;
开发者ID:lsibjornrun,项目名称:shadowsocks-libev,代码行数:66,代码来源:server.c

示例8: dpram_thread

static int dpram_thread(void *data)
{
	int ret = 0;
	//unsigned long flags;
	struct file *filp;

	dpram_task = current;

	daemonize("dpram_thread");
	//reparent_to_init();  // for 2.6 kernel porting : this seems not to be used in driver
	// current->tty = NULL; // for 2.6 kernel porting
	
	strcpy(current->comm, "multipdp");

	/* set signals to accept */
	//spin_lock_irqsave(&current->sigmask_lock, flags); // for 2.6 kernel proting
	siginitsetinv(&current->blocked, sigmask(SIGUSR1));
	//recalc_sigpending(current);
	recalc_sigpending();
	//spin_unlock_irqrestore(&current->sigmask_lock, flags); // for 2.6 kernel proting

	filp = dpram_open();
	if (filp == NULL) {
		goto out;
	}
	dpram_filp = filp;

	/* send start signal */
	complete(&dpram_complete);

	while (1) {
		ret = dpram_poll(filp);

		if (ret == -ERESTARTSYS) {
			if (sigismember(&current->pending.signal, SIGUSR1)) {
				printk(KERN_ERR "MULTIPDP (%s) DPRAM device communication interrupted\n",__func__);
				sigdelset(&current->pending.signal, SIGUSR1);
				recalc_sigpending();
				ret = 0;
				break;
			}
		}
		
		else if (ret < 0) {
			EPRINTK("dpram_poll() failed\n");
			break;
		}
		
		else {
			char ch;
			dpram_read(dpram_filp, &ch, sizeof(ch));

			if (ch == 0x7f) {
				pdp_demux();
			}
		}

		try_to_freeze();
	}

	dpram_close(filp);
	dpram_filp = NULL;

out:
	dpram_task = NULL;

	/* send finish signal and exit */
	complete_and_exit(&dpram_complete, ret);
}
开发者ID:sirgatez,项目名称:Android-Eclair-Kernel-Samsung-Modules-Source-v2.6.29.6,代码行数:69,代码来源:multipdp.c

示例9: main

//-----main function------------------------------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
    if (argc == 2)                      //shortcut to daemonize or not
    { if (strcmp(argv[1],"1") == 0) {daemonize();} }

    struct clientParams controlClient[MAXTHREADS];  //array of struct which control the threads
    pthread_t clientThreads[MAXTHREADS]; //array of threads
    int clientSocket[MAXTHREADS];
    int yes = 1;                    //used in setsockopt function

    int sockfd, new_fd;            // listen on sock_fd, new connection on new_fd
    struct sockaddr_in my_addr;    // my address information
    struct sockaddr_in their_addr; // connector's address information
    socklen_t sin_size;

    int i=0;
    FILE *fUser;                    //the users present in the file are copied to the array
    if(fUser=fopen("user.txt","r"))
    {
        while(fscanf(fUser,"%s %s",userInfo[numUsers].user, userInfo[numUsers].pass)==2)
        { numUsers++;}
        fclose(fUser);
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); }
    if (setsockopt(sockfd,SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); }

    my_addr.sin_family = AF_INET;  // host byte order
    my_addr.sin_port = htons(MYPORT);  // short, network byte order
    my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
    memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);

    if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); }
    if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); }

    int reset = 0;              //checks if all the threads are used
    struct timeval timeout;     //used for creating the timeout
    timeout.tv_usec = 0;        //needed as parameter, else timeout doesnt work since it takes any random value

    char recvCheck[DATASIZE];   //recieve the message during timeout, control for setsockopt

    for(;;)
    {
        printf("id: %d Waiting for a connection...\n", getpid());   //since we use 2 threads for each client, other connections with 1 socket are denied
        if ((clientSocket[i] = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept");}   //1st connection

        timeout.tv_sec = 1;      //timeout is set to 1 sec
        if(setsockopt(clientSocket[i], SOL_SOCKET, SO_RCVTIMEO, (struct timeout *)&timeout, sizeof(timeout)) < 0) {perror("setsockopt failed");}
        recv(clientSocket[i], recvCheck, DATASIZE, 0);      //recv is active for 1 sec
        timeout.tv_sec = 0;      //timeout is disabled
        if(setsockopt(clientSocket[i], SOL_SOCKET, SO_RCVTIMEO, (struct timeout *)&timeout, sizeof(timeout)) < 0) {perror("setsockopt failed");}

        if (strcmp(recvCheck, "thing") == 0)        //if the right string was recieved during 1 sec, accept the connection from next socket, run the program
        {
            printf("I got the right thing.\n");
            if ((clientSocket[i+1] = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept");}
            printf("Accepted Connections\n");

            if (reset)              //if reset=1, join present i and i+1 threads before creating new threads
            {
                pthread_tryjoin_np(clientThreads[i], NULL);
                pthread_tryjoin_np(clientThreads[i+1], NULL);
            }
            printf("Creating thread %d\n", i);      //Thread 1: listener function
            controlClient[i].threadId=i;
            controlClient[i].clientSocket=clientSocket[i];
            controlClient[i].recvError = 0;
            pthread_create(&clientThreads[i], NULL, &serverListener, &controlClient[i]);

            printf("Creating thread %d\n", i+1);     //Thread 2: sender function
            controlClient[i+1].threadId=(i+1);
            controlClient[i+1].clientSocket=clientSocket[i+1];
            controlClient[i+1].recvError = 0;
            pthread_create(&clientThreads[i+1], NULL, &serverSender, &controlClient[i+1]);

            i+=2;                //increased by 2 since threads work in pairs

            if (i == MAXTHREADS) //if all threads are used, start over from 0
            { i = 0; reset = 1; }

            strcpy(recvCheck, " "); //reset the recvCheck to check further incoming connections
        }
        else            //if nothing or something wrong with one socket was recieved, close the current socket and restart the loop
        {
            printf("I didnt get the right thing. Closing socket.\n");
            close(clientSocket[i]);
        }
    }
    return 0;
}
开发者ID:OlSom,项目名称:Chess,代码行数:91,代码来源:ThreadedServer.c

示例10: init


//.........这里部分代码省略.........
			break;
#ifdef __linux__
		case 'S':
			SETFLAG(SYSTEMD_MASK);
			break;
#endif
		case 'V':
			printf("Version " MINIDLNA_VERSION "\n");
			exit(0);
			break;
		default:
			DPRINTF(E_ERROR, L_GENERAL, "Unknown option: %s\n", argv[i]);
		}
	}
	/* If no IP was specified, try to detect one */
	if (n_lan_addr < 1)
	{
		if (getsysaddrs() <= 0)
			DPRINTF(E_FATAL, L_GENERAL, "No IP address automatically detected!\n");
	}

	if (!n_lan_addr || runtime_vars.port <= 0)
	{
		DPRINTF(E_ERROR, L_GENERAL, "Usage:\n\t"
		        "%s [-d] [-v] [-f config_file]\n"
			"\t\t[-a listening_ip] [-p port]\n"
			/*"[-l logfile] " not functionnal */
			"\t\t[-s serial] [-m model_number] \n"
			"\t\t[-t notify_interval] [-P pid_filename]\n"
			"\t\t[-u uid_to_run_as]\n"
			"\t\t[-w url] [-R] [-V] [-h]\n"
		        "\nNotes:\n\tNotify interval is in seconds. Default is 895 seconds.\n"
			"\tDefault pid file is %s.\n"
			"\tWith -d minidlna will run in debug mode (not daemonize).\n"
			"\t-w sets the presentation url. Default is http address on port 80\n"
			"\t-h displays this text\n"
			"\t-R forces a full rescan\n"
			"\t-L do note create playlists\n"
#ifdef __linux__
			"\t-S changes behaviour for systemd\n"
#endif
			"\t-V print the version number\n",
		        argv[0], pidfilename);
		return 1;
	}

	if (verbose_flag)
	{
		strcpy(log_str+65, "debug");
		log_level = log_str;
	}
	else if (!log_level)
		log_level = log_str;

	/* Set the default log file path to NULL (stdout) */
	path = NULL;
	if (debug_flag)
	{
		pid = getpid();
		strcpy(log_str+65, "maxdebug");
		log_level = log_str;
	}
	else if (GETFLAG(SYSTEMD_MASK))
	{
		pid = getpid();
	}
开发者ID:ashwing920,项目名称:minidlna,代码行数:67,代码来源:minidlna.c

示例11: main

int main(int argc, char **argv) {
    void *mod_routing = NULL;
    char *conffile = NULL;
    FILE *file = NULL;
    int nofork = 1;
    char str[100];
    int c = 0;
    char b_log  = 1;
    char b_fork = 1;
    memset(&str, 0, 100*sizeof(char));
    log_init("logFile",NULL);
    log2display(LOG_ALERT);

    p_threadpool = threadpool_create(5, 8096, 0);

    init_maps();
    init_call_id(NULL);

    while((c=getopt(argc, argv, "c:vP:fhD:"))!=-1) {
        switch(c) {
        case 'c':
            conffile = optarg;
            break;
        case 'v':
            printf("sip2smpp version: %s\n", VERSION);
            exit(0);
            break;
        case 'P':
            pid_file = optarg;
            break;
        case 'f':
            nofork = 0;
            b_fork = 0;
            break;
        case 'h':
            usage(0);
            break;
        case 'D':
        {
            char log = atoi(optarg);
            if(log >= 0 && log <= 8) {
                log2display((Loglevel)log);
                b_log = 0;
            }
            break;
        }
        default:
            abort();
        }
    }

    if(!conffile) {
        conffile = (char*)malloc(sizeof(char)*strlen(DEFAULT_CONFIG)+1);
        strcpy(conffile,DEFAULT_CONFIG);
    }

    if((file = fopen(conffile,"r")) != NULL) {
        fclose(file);
    } else {
        ERROR(LOG_FILE | LOG_SCREEN,"The INI file isn't found!");
        handler(-1);
    }

    if(load_config_file((uint8_t*)conffile, CONFIG_ALL, NULL) == -1) {
        ERROR(LOG_FILE | LOG_SCREEN,"There are errors in the INI file!");
        free_config_file(CONFIG_ALL, NULL);
        handler(-1);
    }

    if(b_log) {
        log2display((Loglevel)cfg_main->log_level);
    }

    if(b_fork) {
        nofork = !cfg_main->fork;
    }

    if(daemonize(nofork) != 0) {
        ERROR(LOG_FILE | LOG_SCREEN,"Daemoniize failed");
        exit(-1);
    }

    //Load routing module
    void* functions[2] = { send_sms_to_smpp, send_sms_to_sip };
    void* cfgs[2] = { cfg_smpp, cfg_sip };
    if(cfg_main->routing_module) {
        mod_routing = dlopen(cfg_main->routing_module, RTLD_NOW | RTLD_GLOBAL);
        if(!mod_routing) {
            ERROR(LOG_SCREEN | LOG_FILE, "%s", dlerror());
            handler(-1);
        }
        f_start_routing = dlsym(mod_routing, "start_routing");
        f_routing       = dlsym(mod_routing, "routing");
        f_close_routing = dlsym(mod_routing, "close_routing");
    } else {
        f_start_routing = default_start_routing;
        f_routing       = default_routing;
        f_close_routing = default_close_routing;
    }

//.........这里部分代码省略.........
开发者ID:fairwaves,项目名称:sip2smpp,代码行数:101,代码来源:main.c

示例12: create_everything


//.........这里部分代码省略.........
	mc.silent_timeout = silent_timeout;
	mc.final_timeout = final_timeout;
	mc.delete_delay = delete_delay;
	mc.default_tos = tos;
	mc.b2b_url = b2b_url;
	mc.fmt = xmlrpc_fmt;
	mc.graphite_ep = graphite_ep;
	mc.graphite_interval = graphite_interval;
	mc.redis_subscribed_keyspaces = g_queue_copy(&keyspaces);

	if (redis_num_threads < 1) {
#ifdef _SC_NPROCESSORS_ONLN
		redis_num_threads = sysconf( _SC_NPROCESSORS_ONLN );
#endif
		if (redis_num_threads < 1) {
			redis_num_threads = REDIS_RESTORE_NUM_THREADS;
		}
	}
	mc.redis_num_threads = redis_num_threads;

	ct = NULL;
	if (tcp_listen_ep.port) {
		ct = control_tcp_new(ctx->p, &tcp_listen_ep, ctx->m);
		if (!ct)
			die("Failed to open TCP control connection port");
	}

	cu = NULL;
	if (udp_listen_ep.port) {
		interfaces_exclude_port(udp_listen_ep.port);
		cu = control_udp_new(ctx->p, &udp_listen_ep, ctx->m);
		if (!cu)
			die("Failed to open UDP control connection port");
	}

	cn = NULL;
	if (ng_listen_ep.port) {
		interfaces_exclude_port(ng_listen_ep.port);
		cn = control_ng_new(ctx->p, &ng_listen_ep, ctx->m);
		if (!cn)
			die("Failed to open UDP control connection port");
	}

	cl = NULL;
	if (cli_listen_ep.port) {
		interfaces_exclude_port(cli_listen_ep.port);
	    cl = cli_new(ctx->p, &cli_listen_ep, ctx->m);
	    if (!cl)
	        die("Failed to open UDP CLI connection port");
	}

	if (!is_addr_unspecified(&redis_write_ep.address)) {
		mc.redis_write = redis_new(&redis_write_ep, redis_write_db, redis_write_auth, ANY_REDIS_ROLE, no_redis_required);
		if (!mc.redis_write)
			die("Cannot start up without running Redis %s write database! See also NO_REDIS_REQUIRED paramter.",
				endpoint_print_buf(&redis_write_ep));
	}

	if (!is_addr_unspecified(&redis_ep.address)) {
		mc.redis = redis_new(&redis_ep, redis_db, redis_auth, mc.redis_write ? ANY_REDIS_ROLE : MASTER_REDIS_ROLE, no_redis_required);
		mc.redis_notify = redis_new(&redis_ep, redis_db, redis_auth, mc.redis_write ? ANY_REDIS_ROLE : MASTER_REDIS_ROLE, no_redis_required);
		if (!mc.redis || !mc.redis_notify)
			die("Cannot start up without running Redis %s database! See also NO_REDIS_REQUIRED paramter.",
				endpoint_print_buf(&redis_ep));

		if (!mc.redis_write)
			mc.redis_write = mc.redis;
	}

	mc.redis_expires_secs = redis_expires;

	ctx->m->conf = mc;

	if (!foreground)
		daemonize();
	wpidfile();

	ctx->m->homer = homer_sender_new(&homer_ep, homer_protocol, homer_id);

	if (mc.redis) {
		// start redis restore timer
		gettimeofday(&redis_start, NULL);

		// restore
		if (redis_restore(ctx->m, mc.redis))
			die("Refusing to continue without working Redis database");

		// stop redis restore timer
		gettimeofday(&redis_stop, NULL);

		// print redis restore duration
		redis_diff += timeval_diff(&redis_stop, &redis_start) / 1000.0;
		ilog(LOG_INFO, "Redis restore time = %.0lf ms", redis_diff);
	}

	gettimeofday(&ctx->m->latest_graphite_interval_start, NULL);

	timeval_from_us(&tmp_tv, graphite_interval*1000000);
	set_graphite_interval_tv(&tmp_tv);
}
开发者ID:onsip,项目名称:rtpengine,代码行数:101,代码来源:main.c

示例13: init


//.........这里部分代码省略.........
		case 'V':
			printf("Version " DLNAPROXY_VERSION "\n");
			exit(0);
			break;
		default:
			fprintf(stderr, "Unknown option: %s\n", argv[i]);
		}
	}
	/* If no IP was specified, try to detect one */
	if( n_lan_addr < 1 )
	{
		if( (getsysaddr(ip_addr, sizeof(ip_addr)) < 0) &&
		    (getifaddr("eth0", ip_addr, sizeof(ip_addr)) < 0) &&
		    (getifaddr("eth1", ip_addr, sizeof(ip_addr)) < 0) )
		{
			DPRINTF(E_OFF, L_GENERAL, "No IP address automatically detected!\n");
		}
		if( *ip_addr && parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0 )
		{
			n_lan_addr++;
		}
	}

	if( (n_lan_addr==0) || (runtime_vars.port<=0) )
	{
		fprintf(stderr, "Usage:\n\t"
		        "%s [-d] [-f config_file]\n"
			"\t\t[-a listening_ip] [-p port]\n"
			/*"[-l logfile] " not functionnal */
			"\t\t[-t notify_interval] [-P pid_filename]\n"
			"\t\t[-V] [-h]\n"
		        "\nNotes:\n\tNotify interval is in seconds. Default is 895 seconds.\n"
			"\tDefault pid file is %s.\n"
			"\tWith -d dlnaproxy will run in debug mode (not daemonize).\n"
			"\t-h displays this text\n"
			"\t-V print the version number\n",
		        argv[0], pidfilename);
		return 1;
	}

	if(debug_flag)
	{
		pid = getpid();
		log_init(NULL, "general,inotify,http,ssdp=debug");
	}
	else
	{
#ifdef USE_DAEMON
		if(daemon(0, 0)<0) {
			perror("daemon()");
		}
		pid = getpid();
#else
		pid = daemonize();
#endif
		if( access(log_path, F_OK) != 0 )
			make_dir(log_path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
		sprintf(real_path, "%s/dlnaproxy.log", log_path);
		log_init(real_path, "general,inotify,http,ssdp=warn");
	}

	if(checkforrunning(pidfilename) < 0)
	{
		DPRINTF(E_ERROR, L_GENERAL, "DLNAProxy is already running. EXITING.\n");
		return 1;
	}	
开发者ID:zyclonite,项目名称:dlnaproxy,代码行数:67,代码来源:dlnaproxy.c

示例14: main

int main(int argc, char **argv) {
    struct sigaction sa;
    char *cmdline_str;
    char **argv_array;
    GMainLoop *loop;

    argv_array = argv_to_array(argc, argv);
    cmdline_str = get_command_line(argv_array);
    set_argv_for_child_process(argv_array);

    cps_config_init(argc, argv);

    if(global_config.daemonize) {
        /* When daemonizing, a child process will be launched with daemonization disabled */
        daemonize();
        run_watchdog(argv_array);
        /* Watchdog should never stop ! */
        exit(EXIT_FAILURE);
    }

    /* The child (or not daemonized process) will continue here. */
    L (LOGLEVEL_WARNING, PACKAGE_NAME "-" PACKAGE_VERSION " starting");
    L (LOGLEVEL_DEBUG, "Command line : %s", cmdline_str);
    g_free(cmdline_str);

    /* Signals initialization {{{ */
    memset (&sa, 0, sizeof (sa));
    sa.sa_sigaction = signal_handler_for_stop;
    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&(sa.sa_mask));
    if(0 != sigaction(SIGTERM, &sa, NULL)) {
        L (LOGLEVEL_CRITICAL, "Could not set signal handler for TERM");
        exit(EXIT_FAILURE);
    }
    if(0 != sigaction(SIGINT, &sa, NULL)) {
        L (LOGLEVEL_CRITICAL, "Could not set signal handler for INT");
        close_all_and_exit(EXIT_FAILURE);
    }

    if(0 != sigaction(SIGQUIT, &sa, NULL)) {
        L (LOGLEVEL_CRITICAL, "Could not set signal handler for QUIT");
        close_all_and_exit(EXIT_FAILURE);
    }

    memset (&sa, 0, sizeof (sa));
    sa.sa_handler = SIG_IGN;
    sa.sa_flags = SA_RESTART;
    sigemptyset(&(sa.sa_mask));
    if(0 != sigaction(SIGPIPE, &sa, NULL)) {
        L (LOGLEVEL_CRITICAL, "Could not set signal handler for PIPE");
        exit(EXIT_FAILURE);
    }

    /* }}} */

    cpsa_init();

    loop = g_main_new(TRUE);
    g_timeout_add_seconds(global_config.agent__interval, cpsa_get_process, NULL);

    g_main_run( loop );

    L (LOGLEVEL_WARNING, PACKAGE_NAME "-" PACKAGE_VERSION " ending");

    exit(EXIT_SUCCESS);
}
开发者ID:perfwatcher,项目名称:collectps,代码行数:66,代码来源:main.c

示例15: dvb_frontend_thread

static int dvb_frontend_thread(void *data)
{
    struct dvb_frontend *fe = data;
    struct dvb_frontend_private *fepriv = fe->frontend_priv;
    unsigned long timeout;
    char name [15];
    fe_status_t s;
    struct dvb_frontend_parameters *params;

    dprintk("%s\n", __FUNCTION__);

    snprintf (name, sizeof(name), "kdvb-fe-%i", fe->dvb->num);

    lock_kernel();
    daemonize(name);
    sigfillset(&current->blocked);
    unlock_kernel();

    fepriv->check_wrapped = 0;
    fepriv->quality = 0;
    fepriv->delay = 3*HZ;
    fepriv->status = 0;
    fepriv->wakeup = 0;
    fepriv->reinitialise = 0;

    dvb_frontend_init(fe);

    while (1) {
        up(&fepriv->sem);	    /* is locked when we enter the thread... */

        timeout = wait_event_interruptible_timeout(fepriv->wait_queue,
                  dvb_frontend_should_wakeup(fe),
                  fepriv->delay);
        if (0 != dvb_frontend_is_exiting(fe)) {
            /* got signal or quitting */
            break;
        }

        try_to_freeze();

        if (down_interruptible(&fepriv->sem))
            break;

        if (fepriv->reinitialise) {
            dvb_frontend_init(fe);
            if (fepriv->tone != -1) {
                fe->ops.set_tone(fe, fepriv->tone);
            }
            if (fepriv->voltage != -1) {
                fe->ops.set_voltage(fe, fepriv->voltage);
            }
            fepriv->reinitialise = 0;
        }

        /* do an iteration of the tuning loop */
        if (fe->ops.get_frontend_algo) {
            if (fe->ops.get_frontend_algo(fe) == FE_ALGO_HW) {
                /* have we been asked to retune? */
                params = NULL;
                if (fepriv->state & FESTATE_RETUNE) {
                    params = &fepriv->parameters;
                    fepriv->state = FESTATE_TUNED;
                }

                fe->ops.tune(fe, params, fepriv->tune_mode_flags, &fepriv->delay, &s);
                if (s != fepriv->status) {
                    dvb_frontend_add_event(fe, s);
                    fepriv->status = s;
                }
            } else
                dvb_frontend_swzigzag(fe);
        } else
            dvb_frontend_swzigzag(fe);
    }

    if (dvb_shutdown_timeout) {
        if (dvb_powerdown_on_sleep)
            if (fe->ops.set_voltage)
                fe->ops.set_voltage(fe, SEC_VOLTAGE_OFF);
        if (fe->ops.tuner_ops.sleep) {
            fe->ops.tuner_ops.sleep(fe);
            if (fe->ops.i2c_gate_ctrl)
                fe->ops.i2c_gate_ctrl(fe, 0);
        }
        if (fe->ops.sleep)
            fe->ops.sleep(fe);
    }

    fepriv->thread_pid = 0;
    mb();

    dvb_frontend_wakeup(fe);
    return 0;
}
开发者ID:FatSunHYS,项目名称:OSCourseDesign,代码行数:94,代码来源:dvb_frontend.c


注:本文中的daemonize函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。