您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ tzset函数代码示例

51自学网 2021-06-03 09:02:41
  C++
这篇教程C++ tzset函数代码示例写得很实用,希望能帮到您。

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

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

示例1: N_NOINLINE

NIM_EXTERNC N_NOINLINE(void, stdlib_timesInit)(void) {	tzset();}
开发者ID:jlp765,项目名称:csources,代码行数:3,


示例2: main

intmain(int argc, char **argv){    int c;    int forkaway = 0;    FILE *pidfile;    const char *pidpath = "/var/run/tvheadend.pid";    struct group *grp;    struct passwd *pw;    const char *usernam = NULL;    const char *groupnam = NULL;    int logfacility = LOG_DAEMON;    int createdefault = 0;    sigset_t set;    const char *homedir;    const char *rawts_input = NULL;    const char *join_transport = NULL;    const char *confpath = NULL;    char *p, *endp;    uint32_t adapter_mask = 0xffffffff;    int crash = 0;    // make sure the timezone is set    tzset();    while((c = getopt(argc, argv, "Aa:fp:u:g:c:Chdr:j:s")) != -1) {        switch(c) {        case 'a':            adapter_mask = 0x0;            p = strtok(optarg, ",");            if (p != NULL) {                do {                    int adapter = strtol(p, &endp, 10);                    if (*endp != 0 || adapter < 0 || adapter > 31) {                        fprintf(stderr, "Invalid adapter number '%s'/n", p);                        return 1;                    }                    adapter_mask |= (1 << adapter);                } while ((p = strtok(NULL, ",")) != NULL);                if (adapter_mask == 0x0) {                    fprintf(stderr, "No adapters specified!/n");                    return 1;                }            } else {                usage(argv[0]);            }            break;        case 'A':            crash = 1;            break;        case 'f':            forkaway = 1;            break;        case 'p':            pidpath = optarg;            break;        case 'u':            usernam = optarg;            break;        case 'g':            groupnam = optarg;            break;        case 'c':            confpath = optarg;            break;        case 'd':            log_debug_to_console = 1;            break;        case 's':            log_debug_to_syslog = 1;            break;        case 'C':            createdefault = 1;            break;        case 'r':            rawts_input = optarg;            break;        case 'j':            join_transport = optarg;            break;        default:            usage(argv[0]);        }    }    signal(SIGPIPE, handle_sigpipe);    if(forkaway) {        grp  = getgrnam(groupnam ?: "video");        pw   = usernam ? getpwnam(usernam) : NULL;        if(daemon(0, 0)) {            exit(2);        }        pidfile = fopen(pidpath, "w+");        if(pidfile != NULL) {            fprintf(pidfile, "%d/n", getpid());            fclose(pidfile);        }//.........这里部分代码省略.........
开发者ID:stev47,项目名称:tvheadend,代码行数:101,


示例3: main

//.........这里部分代码省略.........		{			plugins_free(srv);			server_free(srv);			return -1;		}#ifdef HAVE_PWD_H		/*		 * Change group before chroot, when we have access		 * to /etc/group		 * */		if (srv->srvconf.groupname->used)		{			setgid(grp->gr_gid);			setgroups(0, NULL); //返回用户组的数目。			if (srv->srvconf.username->used)			{				//Initialize the group access list by reading the group database /etc/group and using all groups of which				//user is a member.  The additional group group is also added to the list.				initgroups(srv->srvconf.username->ptr, grp->gr_gid);			}		}#endif#ifdef HAVE_CHROOT		if (srv->srvconf.changeroot->used)		{			//The tzset() function initializes the tzname variable from the TZ environment variable.  			//This function is automatically called by the other time conversion functions that depend 			//on the time zone.  			//In a SysV-like environment it will also set the variables  time-zone  (seconds  West  of GMT) 			//and daylight 			//(0 if this time zone does not have any daylight saving time rules, nonzero if there is a			//time during the year when daylight saving time applies).			tzset();			//设置程序所参考的根目录,将被所有的子进程继承。			//也就是对于本程序而言,"/"并不是系统的根目录,而是这设置的目录。			if (-1 == chroot(srv->srvconf.changeroot->ptr))			{				log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));				return -1;			}			//修改工作目录.			/*			 * 注意:			 * 		由于前面已经设置了根目录。因此这里将工作目录切换到"/"并不是系统的根目录,而是			 * 		上面通过函数chroot设置的根目录。			 */			if (-1 == chdir("/"))			{				log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));				return -1;			}		}#endif#ifdef HAVE_PWD_H		/*		 * drop root privs 放弃超级管理员权限。		 */		if (srv->srvconf.username->used)		{			setuid(pwd->pw_uid);		}#endif#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)		/**
开发者ID:kernelhcy,项目名称:hcyprojects,代码行数:67,


示例4: tzset

  Time* Time::from_array(STATE, Object* self,                       Fixnum* sec, Fixnum* min, Fixnum* hour,                      Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* usec,                      Fixnum* isdst, Object* from_gmt) {    struct tm tm;    tm.tm_sec = sec->to_native();    if(tm.tm_sec < 0 || tm.tm_sec > 60) {      Exception::argument_error(state, "sec must be in 0..60");    }    tm.tm_min = min->to_native();    if(tm.tm_min < 0 || tm.tm_min > 60) {      Exception::argument_error(state, "min must be in 0..60");    }    tm.tm_hour = hour->to_native();    if(tm.tm_hour < 0 || tm.tm_hour > 24) {      Exception::argument_error(state, "hour must be in 0..24");    }    tm.tm_mday = mday->to_native();    if(tm.tm_mday < 1 || tm.tm_mday > 31) {      Exception::argument_error(state, "mday must be in 1..31");    }    tm.tm_mon = mon->to_native() - 1;    if(tm.tm_mon < 0 || tm.tm_mon > 11) {      Exception::argument_error(state, "mon must be in 0..11");    }    tm.tm_wday = -1;#ifdef HAVE_TM_GMTOFF    tm.tm_gmtoff = 0;#endif#ifdef HAVE_TM_ZONE    tm.tm_zone = 0;#endif    tm.tm_year = year->to_native() - 1900;    tm.tm_isdst = isdst->to_native();    time_t seconds = -1;    if(RTEST(from_gmt)) {      seconds = ::timegm(&tm);    } else {      tzset();      seconds = ::mktime(&tm);    }    int err = 0;    if(seconds == -1) {      int utc_p = from_gmt->true_p() ? 1 : 0;      seconds = mktime_extended(&tm, utc_p, &err);    }    if(err) return (Time*)Primitives::failure();    Time* obj = state->new_object<Time>(as<Class>(self));    obj->seconds_ = seconds;    obj->microseconds_ = usec->to_native();    obj->is_gmt(state, RTEST(from_gmt) ? Qtrue : Qfalse);    return obj;  }
开发者ID:ConradIrwin,项目名称:rubinius,代码行数:67,


示例5: ns_os_tzset

voidns_os_tzset(void) {#ifdef HAVE_TZSET	tzset();#endif}
开发者ID:2014-class,项目名称:freerouter,代码行数:6,


示例6: main

intmain( int argc, char** argv )    {    char* cp;    struct passwd* pwd;    uid_t uid;    gid_t gid;    char cwd[MAXPATHLEN];    FILE* logfp;    int num_ready;    int cnum, ridx;    connecttab* c;    httpd_conn* hc;    httpd_sockaddr sa4;    httpd_sockaddr sa6;    int gotv4, gotv6;    struct timeval tv;    argv0 = argv[0];    cp = strrchr( argv0, '/' );    if ( cp != (char*) 0 )	++cp;    else	cp = argv0;    openlog( cp, LOG_NDELAY|LOG_PID, LOG_FACILITY );    /* Handle command-line arguments. */    parse_args( argc, argv );    /* Check port number. */    if ( port <= 0 )	{	syslog( LOG_CRIT, "illegal port number" );	(void) fprintf( stderr, "%s: illegal port number/n", argv0 );	exit( 1 );	}    /* Read zone info now, in case we chroot(). */    tzset();    /* Look up hostname now, in case we chroot(). */    lookup_hostname( &sa4, sizeof(sa4), &gotv4, &sa6, sizeof(sa6), &gotv6 );    if ( ! ( gotv4 || gotv6 ) )	{	syslog( LOG_ERR, "can't find any valid address" );	(void) fprintf( stderr, "%s: can't find any valid address/n", argv0 );	exit( 1 );	}    /* Throttle file. */    numthrottles = 0;    maxthrottles = 0;    throttles = (throttletab*) 0;    if ( throttlefile != (char*) 0 )	read_throttlefile( throttlefile );    /* Log file. */    if ( logfile != (char*) 0 )	{	if ( strcmp( logfile, "/dev/null" ) == 0 )	    {	    no_log = 1;	    logfp = (FILE*) 0;	    }	else	    {	    logfp = fopen( logfile, "a" );	    if ( logfp == (FILE*) 0 )		{		syslog( LOG_CRIT, "%.80s - %m", logfile );		perror( logfile );		exit( 1 );		}	    (void) fcntl( fileno( logfp ), F_SETFD, 1 );	    }	}    else	logfp = (FILE*) 0;    /* Figure out uid/gid from user. */    pwd = getpwnam( user );    if ( pwd == (struct passwd*) 0 )	{	syslog( LOG_CRIT, "unknown user - '%.80s'", user );	(void) fprintf( stderr, "%s: unknown user - '%s'/n", argv0, user );	exit( 1 );	}    uid = pwd->pw_uid;    gid = pwd->pw_gid;    /* Switch directories if requested. */    if ( dir != (char*) 0 )	{	if ( chdir( dir ) < 0 )	    {	    syslog( LOG_CRIT, "chdir - %m" );	    perror( "chdir" );	    exit( 1 );	    }//.........这里部分代码省略.........
开发者ID:tisrael,项目名称:thttpd-2.21b,代码行数:101,


示例7: main

intmain(int argc, char *argv[]){	struct tm local;	struct timeval tv, *stv;	struct timezone tz, *stz;	int kern_offset, wall_clock, disrtcset;	size_t len;	/* Avoid time_t here, can be unsigned long or worse */	long offset, localsec, diff;	time_t initial_sec, final_sec;	int ch;	int initial_isdst = -1, final_isdst;	int need_restore = False, sleep_mode = False, looping,	    init = Unknown;	sigset_t mask, emask;	while ((ch = getopt(argc, argv, "ais")) != -1)		switch((char)ch) {		case 'i':               /* initial call, save offset */			if (init != Unknown)				usage();			init = True;			break;		case 'a':               /* adjustment call, use saved offset */			if (init != Unknown)				usage();			init = False;			break;		case 's':			sleep_mode = True;			break;		default:			usage();		}	if (init == Unknown)		usage();	if (access(_PATH_CLOCK, F_OK) != 0)		return 0;	if (init)		sleep_mode = True;	sigemptyset(&mask);	sigemptyset(&emask);	sigaddset(&mask, SIGTERM);	openlog("adjkerntz", LOG_PID|LOG_PERROR, LOG_DAEMON);	(void) signal(SIGHUP, SIG_IGN);	if (init && daemon(0,#ifdef DEBUG	    1#else	    0#endif	    )) {		syslog(LOG_ERR, "daemon: %m");		return 1;	}again:	(void) sigprocmask(SIG_BLOCK, &mask, NULL);	(void) signal(SIGTERM, fake);	diff = 0;	stv = NULL;	stz = NULL;	looping = False;	wall_clock = (access(_PATH_CLOCK, F_OK) == 0);	if (init && !sleep_mode) {		init = False;		if (!wall_clock)			return 0;	}	tzset();	len = sizeof(kern_offset);	if (sysctlbyname("machdep.adjkerntz", &kern_offset, &len, NULL, 0) == -1) {		syslog(LOG_ERR, "sysctl(/"machdep.adjkerntz/"): %m");		return 1;	}/****** Critical section, do all things as fast as possible ******/	/* get local CMOS clock and possible kernel offset */	if (gettimeofday(&tv, &tz)) {		syslog(LOG_ERR, "gettimeofday: %m");		return 1;	}	/* get the actual local timezone difference */	initial_sec = tv.tv_sec;recalculate:	local = *localtime(&initial_sec);//.........这里部分代码省略.........
开发者ID:AhmadTux,项目名称:freebsd,代码行数:101,


示例8: main

intmain (int argc, char *argv[], char **envp){  int index;  set_program_name (argv[0]);#ifdef HAVE_TZSET  tzset ();			/* In case no timezone database in ~ftp.  */#endif#ifdef HAVE_INITSETPROCTITLE  /* Save start and extent of argv for setproctitle.  */  initsetproctitle (argc, argv, envp);#endif /* HAVE_INITSETPROCTITLE */  /* Parse the command line */  iu_argp_init ("ftpd", default_program_authors);  argp_parse (&argp, argc, argv, 0, &index, NULL);    /* Bail out, wrong usage */  argc -= index;  if (argc != 0)    error (1, 0, "surplus arguments; try `%s --help' for more info",	   program_name);  /* LOG_NDELAY sets up the logging connection immediately,     necessary for anonymous ftp's that chroot and can't do it later.  */  openlog ("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);  freopen (PATH_DEVNULL, "w", stderr);  /* If not running via inetd, we detach and dup(fd, 0), dup(fd, 1) the     fd = accept(). tcpd is check if compile with the support  */  if (daemon_mode)    {      if (server_mode (pid_file, &his_addr) < 0)	exit (1);    }  else    {      socklen_t addrlen = sizeof (his_addr);      if (getpeername (STDIN_FILENO, (struct sockaddr *) &his_addr,		       &addrlen) < 0)	{	  syslog (LOG_ERR, "getpeername (%s): %m", program_name);	  exit (1);	}    }  signal (SIGHUP, sigquit);  signal (SIGINT, sigquit);  signal (SIGQUIT, sigquit);  signal (SIGTERM, sigquit);  signal (SIGPIPE, lostconn);  signal (SIGCHLD, SIG_IGN);  if (signal (SIGURG, myoob) == SIG_ERR)    syslog (LOG_ERR, "signal: %m");  /* Get info on the ctrl connection.  */  {    socklen_t addrlen = sizeof (ctrl_addr);    if (getsockname (STDIN_FILENO, (struct sockaddr *) &ctrl_addr,		     &addrlen) < 0)      {	syslog (LOG_ERR, "getsockname (%s): %m", program_name);	exit (1);      }  }#if defined (IP_TOS) && defined (IPTOS_LOWDELAY) && defined (IPPROTO_IP)  /* To  minimize delays for interactive traffic.  */  {    int tos = IPTOS_LOWDELAY;    if (setsockopt (STDIN_FILENO, IPPROTO_IP, IP_TOS,		    (char *) &tos, sizeof (int)) < 0)      syslog (LOG_WARNING, "setsockopt (IP_TOS): %m");  }#endif#ifdef SO_OOBINLINE  /* Try to handle urgent data inline.  */  {    int on = 1;    if (setsockopt (STDIN_FILENO, SOL_SOCKET, SO_OOBINLINE,		    (char *) &on, sizeof (on)) < 0)      syslog (LOG_ERR, "setsockopt: %m");  }#endif#ifdef SO_KEEPALIVE  /* Set keepalives on the socket to detect dropped connections.  */  {    int keepalive = 1;    if (setsockopt (STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE,		    (char *) &keepalive, sizeof (keepalive)) < 0)      syslog (LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");  }#endif#ifdef	F_SETOWN//.........这里部分代码省略.........
开发者ID:DanielMSchmidt,项目名称:it-sec,代码行数:101,


示例9: PyInit_timezone

static voidPyInit_timezone(PyObject *m) {    /* This code moved from PyInit_time wholesale to allow calling it from    time_tzset. In the future, some parts of it can be moved back    (for platforms that don't HAVE_WORKING_TZSET, when we know what they    are), and the extraneous calls to tzset(3) should be removed.    I haven't done this yet, as I don't want to change this code as    little as possible when introducing the time.tzset and time.tzsetwall    methods. This should simply be a method of doing the following once,    at the top of this function and removing the call to tzset() from    time_tzset():        #ifdef HAVE_TZSET        tzset()        #endif    And I'm lazy and hate C so nyer.     */#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)    PyObject *otz0, *otz1;    tzset();#ifdef PYOS_OS2    PyModule_AddIntConstant(m, "timezone", _timezone);#else /* !PYOS_OS2 */    PyModule_AddIntConstant(m, "timezone", timezone);#endif /* PYOS_OS2 */#ifdef HAVE_ALTZONE    PyModule_AddIntConstant(m, "altzone", altzone);#else#ifdef PYOS_OS2    PyModule_AddIntConstant(m, "altzone", _timezone-3600);#else /* !PYOS_OS2 */    PyModule_AddIntConstant(m, "altzone", timezone-3600);#endif /* PYOS_OS2 */#endif    PyModule_AddIntConstant(m, "daylight", daylight);    otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);    otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);    PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/#ifdef HAVE_STRUCT_TM_TM_ZONE    {#define YEAR ((time_t)((365 * 24 + 6) * 3600))        time_t t;        struct tm *p;        long janzone, julyzone;        char janname[10], julyname[10];        t = (time((time_t *)0) / YEAR) * YEAR;        p = localtime(&t);        janzone = -p->tm_gmtoff;        strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);        janname[9] = '/0';        t += YEAR/2;        p = localtime(&t);        julyzone = -p->tm_gmtoff;        strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);        julyname[9] = '/0';        if( janzone < julyzone ) {            /* DST is reversed in the southern hemisphere */            PyModule_AddIntConstant(m, "timezone", julyzone);            PyModule_AddIntConstant(m, "altzone", janzone);            PyModule_AddIntConstant(m, "daylight",                                    janzone != julyzone);            PyModule_AddObject(m, "tzname",                               Py_BuildValue("(zz)",                                             julyname, janname));        } else {            PyModule_AddIntConstant(m, "timezone", janzone);            PyModule_AddIntConstant(m, "altzone", julyzone);            PyModule_AddIntConstant(m, "daylight",                                    janzone != julyzone);            PyModule_AddObject(m, "tzname",                               Py_BuildValue("(zz)",                                             janname, julyname));        }    }#else#endif /* HAVE_STRUCT_TM_TM_ZONE */#ifdef __CYGWIN__    tzset();    PyModule_AddIntConstant(m, "timezone", _timezone);    PyModule_AddIntConstant(m, "altzone", _timezone-3600);    PyModule_AddIntConstant(m, "daylight", _daylight);    PyModule_AddObject(m, "tzname",                       Py_BuildValue("(zz)", _tzname[0], _tzname[1]));#endif /* __CYGWIN__ */#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/}
开发者ID:pogigroo,项目名称:py3k-__format__,代码行数:89,


示例10: main

int main( int argc, char **argv )#endif{   struct timeval now_time;   int temp = -1, temp2 = -1;   bool fCopyOver = false;#if !defined(WIN32)   moron_check(  );  // Debatable weather or not this is true in WIN32 anyway :)#endif   DONT_UPPER = false;   num_descriptors = 0;   num_logins = 0;   dlist.clear(  );   mudstrlcpy( lastplayercmd, "No commands issued yet", MIL * 2 );   // Init time.   tzset(  );   gettimeofday( &now_time, NULL );   current_time = now_time.tv_sec;   mudstrlcpy( str_boot_time, c_time( current_time, -1 ), MIL );  /* Records when the mud was last rebooted */   new_pfile_time_t = current_time + 86400;   mud_start_time = current_time;   // Get the port number.   mud_port = 9500;   if( argc > 1 )   {      if( !is_number( argv[1] ) )      {         fprintf( stderr, "Usage: %s [port #]/n", argv[0] );         exit( 1 );      }      else if( ( mud_port = atoi( argv[1] ) ) <= 1024 )      {         fprintf( stderr, "%s", "Port number must be above 1024./n" );         exit( 1 );      }      if( argv[2] && argv[2][0] )      {         fCopyOver = true;         control = atoi( argv[3] );#ifdef IMC         temp2 = atoi( argv[4] );#endif      }      else         fCopyOver = false;   }#if defined(WIN32)   {      /*       * Initialise Windows sockets library        */      unsigned short wVersionRequested = MAKEWORD( 1, 1 );      WSADATA wsadata;      int err;      /*       * Need to include library: wsock32.lib for Windows Sockets        */      err = WSAStartup( wVersionRequested, &wsadata );      if( err )      {         fprintf( stderr, "Error %i on WSAStartup/n", err );         exit( 1 );      }      /*       * standard termination signals        */      signal( SIGINT, bailout );      signal( SIGTERM, bailout );   }#endif /* WIN32 */   // Initialize all startup functions of the mud.    init_mud( fCopyOver, mud_port, temp, temp2 );#if !defined(WIN32)   /*    * Set various signal traps, waiting until after completing all bootup operations    * before doing so because crashes during bootup should not be intercepted. Samson 3-11-04    */   signal( SIGTERM, SigTerm );   /* Catch kill signals */   signal( SIGPIPE, SIG_IGN );   signal( SIGALRM, caught_alarm );   signal( SIGUSR1, SigUser1 );  /* Catch user defined signals */   signal( SIGUSR2, SigUser2 );#endif#ifdef MULTIPORT   signal( SIGCHLD, SigChld );#endif   /*    * If this setting is active, intercept SIGSEGV and keep the mud running.//.........这里部分代码省略.........
开发者ID:locke2002,项目名称:ShruggingMan,代码行数:101,


示例11: vsyslogp_r

voidvsyslogp_r(int pri, struct syslog_data *data, const char *msgid,	const char *sdfmt, const char *msgfmt, va_list ap){	static const char BRCOSP[] = "]: ";	static const char CRLF[] = "/r/n";	size_t cnt, prlen, tries;	char ch, *p, *t;	struct timeval tv;	struct tm tmnow;	time_t now;	int fd, saved_errno;#define TBUF_LEN	2048#define FMT_LEN		1024#define MAXTRIES	10	char tbuf[TBUF_LEN], fmt_cpy[FMT_LEN], fmt_cat[FMT_LEN] = "";	size_t tbuf_left, fmt_left, msgsdlen;	char *fmt = fmt_cat;	int signal_safe = pri & LOG_SIGNAL_SAFE;	struct iovec iov[7];	/* prog + [ + pid + ]: + fmt + crlf */	int opened, iovcnt;	pri &= ~LOG_SIGNAL_SAFE;#define INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID	/* Check for invalid bits. */	if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {		syslog_r(INTERNALLOG | signal_safe, data,		    "syslog_r: unknown facility/priority: %x", pri);		pri &= LOG_PRIMASK|LOG_FACMASK;	}	/* Check priority against setlogmask values. */	if (!(LOG_MASK(LOG_PRI(pri)) & data->log_mask))		return;	saved_errno = errno;	/* Set default facility if none specified. */	if ((pri & LOG_FACMASK) == 0)		pri |= data->log_fac;	/* Build the message. */	p = tbuf;	tbuf_left = TBUF_LEN;#define DEC()							/	do {							/		if (prlen >= tbuf_left)				/			prlen = tbuf_left - 1;			/		p += prlen;					/		tbuf_left -= prlen;				/	} while (/*CONSTCOND*/0)	prlen = snprintf_ss(p, tbuf_left, "<%d>1 ", pri);	DEC();	if (!signal_safe && (gettimeofday(&tv, NULL) != -1)) {		/* strftime() implies tzset(), localtime_r() doesn't. */		tzset();		now = (time_t) tv.tv_sec;		localtime_r(&now, &tmnow);		prlen = strftime(p, tbuf_left, "%FT%T", &tmnow);		DEC();		prlen = snprintf(p, tbuf_left, ".%06ld", (long)tv.tv_usec);		DEC();		prlen = strftime(p, tbuf_left-1, "%z", &tmnow);		/* strftime gives eg. "+0200", but we need "+02:00" */		if (prlen == 5) {			p[prlen+1] = p[prlen];			p[prlen]   = p[prlen-1];			p[prlen-1] = p[prlen-2];			p[prlen-2] = ':';			prlen += 1;		}	} else {		prlen = snprintf_ss(p, tbuf_left, "-");		/* if gmtime_r() was signal-safe we could output the UTC-time:		gmtime_r(&now, &tmnow);		prlen = strftime(p, tbuf_left, "%FT%TZ", &tmnow);		*/	}	DEC();	prlen = snprintf_ss(p, tbuf_left, " %s ", hostname);	DEC();	if (data->log_tag == NULL)		data->log_tag = getprogname();	prlen = snprintf_ss(p, tbuf_left, "%s ",	    data->log_tag ? data->log_tag : "-");	if (data->log_stat & (LOG_PERROR|LOG_CONS)) {		iovcnt = 0;		iov[iovcnt].iov_base = p;		iov[iovcnt].iov_len = prlen - 1;		iovcnt++;	}	DEC();//.........这里部分代码省略.........
开发者ID:DragonQuan,项目名称:minix3,代码行数:101,


示例12: amf_to_json

/* JSON metadata dumping */static void amf_to_json(const amf_data * data, json_t ** object) {    if (data != NULL) {        json_t * value;        amf_node * node;        time_t time;        struct tm * t;        char str[128];        char * escaped_str;        switch (data->type) {            case AMF_TYPE_NUMBER:                sprintf(str, "%.12g", data->number_data);                *object = json_new_number(str);                break;            case AMF_TYPE_BOOLEAN:                *object = (data->boolean_data) ? json_new_true() : json_new_false();                break;            case AMF_TYPE_STRING:                escaped_str = json_escape((char *)amf_string_get_bytes(data));                *object = json_new_string(escaped_str);                free(escaped_str);                break;            case AMF_TYPE_OBJECT:                *object = json_new_object();                node = amf_object_first(data);                while (node != NULL) {                    amf_to_json(amf_object_get_data(node), &value);                    escaped_str = json_escape((char *)amf_string_get_bytes(amf_object_get_name(node)));                    json_insert_pair_into_object(*object, escaped_str, value);                    free(escaped_str);                    node = amf_object_next(node);                }                break;            case AMF_TYPE_NULL:            case AMF_TYPE_UNDEFINED:                *object = json_new_null();                break;            case AMF_TYPE_ASSOCIATIVE_ARRAY:                *object = json_new_object();                node = amf_associative_array_first(data);                while (node != NULL) {                    amf_to_json(amf_associative_array_get_data(node), &value);                    json_insert_pair_into_object(*object, (const char *)amf_string_get_bytes(amf_associative_array_get_name(node)), value);                    node = amf_associative_array_next(node);                }                break;            case AMF_TYPE_ARRAY:                *object = json_new_array();                node = amf_array_first(data);                while (node != NULL) {                    amf_to_json(amf_array_get(node), &value);                    json_insert_child(*object, value);                    node = amf_array_next(node);                }                break;            case AMF_TYPE_DATE:                time = amf_date_to_time_t(data);                tzset();                t = localtime(&time);                strftime(str, sizeof(str), "%Y-%m-%dT%H:%M:%S", t);                *object = json_new_string(str);                break;            case AMF_TYPE_XML: break;            case AMF_TYPE_CLASS: break;            default: break;        }    }}
开发者ID:bygreencn,项目名称:flvmeta,代码行数:69,


示例13: main

intmain(int argc, char **argv){	int ch, np, ret, Xflag = 0;	pcap_handler phandler = dump_packet;	const char *errstr = NULL;	char *pidf = NULL;	ret = 0;	closefrom(STDERR_FILENO + 1);	while ((ch = getopt(argc, argv, "Dxd:f:i:p:s:")) != -1) {		switch (ch) {		case 'D':			Debug = 1;			break;		case 'd':			delay = strtonum(optarg, 5, 60*60, &errstr);			if (errstr)				usage();			break;		case 'f':			filename = optarg;			break;		case 'i':			interface = optarg;			break;		case 'p':			pidf = optarg;			break;		case 's':			snaplen = strtonum(optarg, 0, PFLOGD_MAXSNAPLEN,			    &errstr);			if (snaplen <= 0)				snaplen = DEF_SNAPLEN;			if (errstr)				snaplen = PFLOGD_MAXSNAPLEN;			break;		case 'x':			Xflag++;			break;		default:			usage();		}	}	log_debug = Debug;	argc -= optind;	argv += optind;	/* does interface exist */	if (!if_exists(interface)) {		warn("Failed to initialize: %s", interface);		logmsg(LOG_ERR, "Failed to initialize: %s", interface);		logmsg(LOG_ERR, "Exiting, init failure");		exit(1);	}	if (!Debug) {		openlog("pflogd", LOG_PID | LOG_CONS, LOG_DAEMON);		if (daemon(0, 0)) {			logmsg(LOG_WARNING, "Failed to become daemon: %s",			    strerror(errno));		}		pidfile(pidf);	}	tzset();	(void)umask(S_IRWXG | S_IRWXO);	/* filter will be used by the privileged process */	if (argc) {		filter = copy_argv(argv);		if (filter == NULL)			logmsg(LOG_NOTICE, "Failed to form filter expression");	}	/* initialize pcap before dropping privileges */	if (init_pcap()) {		logmsg(LOG_ERR, "Exiting, init failure");		exit(1);	}	/* Privilege separation begins here */	if (priv_init()) {		logmsg(LOG_ERR, "unable to privsep");		exit(1);	}	setproctitle("[initializing]");	/* Process is now unprivileged and inside a chroot */	signal(SIGTERM, sig_close);	signal(SIGINT, sig_close);	signal(SIGQUIT, sig_close);	signal(SIGALRM, sig_alrm);	signal(SIGUSR1, sig_usr1);	signal(SIGHUP, sig_hup);	alarm(delay);//.........这里部分代码省略.........
开发者ID:coyizumi,项目名称:cs111,代码行数:101,


示例14: main

int main(int argc, char **argv) {	int result;	int error = FALSE;	char *buffer = NULL;	int display_license = FALSE;	int display_help = FALSE;	int c = 0;	struct tm *tm;	time_t current_time;	time_t test_time;	time_t saved_test_time;	time_t next_valid_time = 0L;	time_t chosen_valid_time = 0L;	char datestring[256];	host *temp_host = NULL;	hostgroup *temp_hostgroup = NULL;	hostsmember *temp_member = NULL;	timeperiod *temp_timeperiod = NULL;	int is_valid_time = 0;	int iterations = 1000;	plan_tests(6043);	/* reset program variables */	reset_variables();	printf("Reading configuration data.../n");	config_file = strdup("smallconfig/nagios.cfg");	/* read in the configuration files (main config file, resource and object config files) */	result = read_main_config_file(config_file);	ok(result == OK, "Read main configuration file okay - if fails, use nagios -v to check");	result = read_all_object_data(config_file);	ok(result == OK, "Read all object config files");	result = pre_flight_check();	ok(result == OK, "Preflight check okay");	time(&current_time);	test_time = current_time;	saved_test_time = current_time;	temp_timeperiod = find_timeperiod("none");	is_valid_time = check_time_against_period(test_time, temp_timeperiod);	ok(is_valid_time == ERROR, "No valid time because time period is empty");	get_next_valid_time(current_time, &next_valid_time, temp_timeperiod);	ok(current_time == next_valid_time, "There is no valid time due to timeperiod");	temp_timeperiod = find_timeperiod("24x7");	is_valid_time = check_time_against_period(test_time, temp_timeperiod);	ok(is_valid_time == OK, "Fine because 24x7");	get_next_valid_time(current_time, &next_valid_time, temp_timeperiod);	ok((next_valid_time - current_time) <= 2, "Next valid time should be the current_time, but with a 2 second tolerance");	/* 2009-10-25 is the day when clocks go back an hour in Europe. Bug happens during 23:00 to 00:00 */	/* This is 23:01:01 */	saved_test_time = 1256511661;	saved_test_time = saved_test_time - (24 * 60 * 60);	putenv("TZ=UTC");	tzset();	test_time = saved_test_time;	c = 0;	while(c < iterations) {		is_valid_time = check_time_against_period(test_time, temp_timeperiod);		ok(is_valid_time == OK, "Always OK for 24x7 with TZ=UTC, time_t=%lu", test_time);		chosen_valid_time = 0L;		_get_next_valid_time(test_time, test_time, &chosen_valid_time, temp_timeperiod);		ok(test_time == chosen_valid_time, "get_next_valid_time always returns same time");		test_time += 1800;		c++;		}	putenv("TZ=Europe/London");	tzset();	test_time = saved_test_time;	c = 0;	while(c < iterations) {		is_valid_time = check_time_against_period(test_time, temp_timeperiod);		ok(is_valid_time == OK, "Always OK for 24x7 with TZ=Europe/London, time_t=%lu", test_time);		_get_next_valid_time(test_time, test_time, &chosen_valid_time, temp_timeperiod);		ok(test_time == chosen_valid_time, "get_next_valid_time always returns same time, time_t=%lu", test_time);		test_time += 1800;		c++;		}	/* 2009-11-01 is the day when clocks go back an hour in America. Bug happens during 23:00 to 00:00 */	/* This is 23:01:01 */	saved_test_time = 1256511661;	saved_test_time = saved_test_time - (24 * 60 * 60);	putenv("TZ=America/New_York");	tzset();	test_time = saved_test_time;//.........这里部分代码省略.........
开发者ID:a3linux,项目名称:nagios-amq-perf,代码行数:101,


示例15: main

//.........这里部分代码省略.........				log_error_write(srv, __FILE__, __LINE__, "sb",					"can't find groupname", srv->srvconf.groupname);				return -1;			}			if (grp->gr_gid == 0) {				log_error_write(srv, __FILE__, __LINE__, "s",						"I will not set gid to 0/n");				return -1;			}		}#endif		/* we need root-perms for port < 1024 */		if (0 != network_init(srv)) {			plugins_free(srv);			server_free(srv);			return -1;		}#ifdef HAVE_PWD_H		/* 		 * Change group before chroot, when we have access		 * to /etc/group		 * */		if (NULL != grp) {			setgid(grp->gr_gid);			setgroups(0, NULL);			if (srv->srvconf.username->used) {				initgroups(srv->srvconf.username->ptr, grp->gr_gid);			}		}#endif#ifdef HAVE_CHROOT		if (srv->srvconf.changeroot->used) {			tzset();			if (-1 == chroot(srv->srvconf.changeroot->ptr)) {				log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));				return -1;			}			if (-1 == chdir("/")) {				log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));				return -1;			}		}#endif#ifdef HAVE_PWD_H		/* drop root privs */		if (NULL != pwd) {			setuid(pwd->pw_uid);		}#endif#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)		/**		 * on IRIX 6.5.30 they have prctl() but no DUMPABLE		 */		if (srv->srvconf.enable_cores) {			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);		}#endif	} else {#ifdef HAVE_GETRLIMIT		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {			log_error_write(srv, __FILE__, __LINE__,					"ss", "couldn't get 'max filedescriptors'",					strerror(errno));
开发者ID:Janhouse,项目名称:lighttpd1.4,代码行数:67,


示例16: main

//.........这里部分代码省略.........            }            sbcl_argv[argj] = 0;        }    }    /* Align down to multiple of page_table page size, and to the appropriate     * stack alignment. */    dynamic_space_size &= ~(PAGE_BYTES-1);    thread_control_stack_size &= ~(CONTROL_STACK_ALIGNMENT_BYTES-1);    /* Preserve the runtime options for possible future core saving */    runtime_options->dynamic_space_size = dynamic_space_size;    runtime_options->thread_control_stack_size = thread_control_stack_size;    /* KLUDGE: os_vm_page_size is set by os_init(), and on some     * systems (e.g. Alpha) arch_init() needs need os_vm_page_size, so     * it must follow os_init(). -- WHN 2000-01-26 */    os_init(argv, envp);    arch_init();    gc_init();    validate();    /* If no core file was specified, look for one. */    if (!core) {        core = search_for_core();    }    /* Make sure that SBCL_HOME is set and not the empty string,       unless loading an embedded core. */    if (!(sbcl_home && *sbcl_home) && embedded_core_offset == 0) {        char *envstring, *copied_core, *dir;        char *stem = "SBCL_HOME=";        copied_core = copied_string(core);        dir = dirname(copied_core);        envstring = (char *) calloc(strlen(stem) +                                    strlen(dir) +                                    1,                                    sizeof(char));        sprintf(envstring, "%s%s", stem, dir);        putenv(envstring);        free(copied_core);    }    if (!noinform && embedded_core_offset == 0) {        print_banner();        fflush(stdout);    }#if defined(SVR4) || defined(__linux__)    tzset();#endif    define_var("nil", NIL, 1);    define_var("t", T, 1);    if (!disable_lossage_handler_p)        enable_lossage_handler();    globals_init();    initial_function = load_core_file(core, embedded_core_offset);    if (initial_function == NIL) {        lose("couldn't find initial function/n");    }#ifdef LISP_FEATURE_HPUX    /* -1 = CLOSURE_FUN_OFFSET, 23 = SIMPLE_FUN_CODE_OFFSET, we are     * not in LANGUAGE_ASSEMBLY so we cant reach them. */    return_from_lisp_stub = (void *) ((char *)*((unsigned long *)                 ((char *)initial_function + -1)) + 23);#endif    gc_initialize_pointers();    arch_install_interrupt_handlers();#ifndef LISP_FEATURE_WIN32    os_install_interrupt_handlers();#else/*     wos_install_interrupt_handlers(handler); */    wos_install_interrupt_handlers(&exception_frame);#endif    /* Pass core filename and the processed argv into Lisp. They'll     * need to be processed further there, to do locale conversion.     */    core_string = core;    posix_argv = sbcl_argv;    FSHOW((stderr, "/funcalling initial_function=0x%lx/n",          (unsigned long)initial_function));#ifdef LISP_FEATURE_WIN32    fprintf(stderr, "/n/This is experimental prerelease support for the Windows platform: use/n/at your own risk.  /"Your Kitten of Death awaits!/"/n");    fflush(stdout);    fflush(stderr);#endif    create_initial_thread(initial_function);    lose("CATS.  CATS ARE NICE./n");    return 0;}
开发者ID:r3v01v3r,项目名称:sbcl-tfb,代码行数:101,


示例17: main

//.........这里部分代码省略.........#endif /* HAVE_GETPWNAM */	/* Chroot */#ifdef HAVE_CHROOT	if (nsd.chrootdir && nsd.chrootdir[0]) {		int l = strlen(nsd.chrootdir)-1; /* ends in trailing slash */		if (file_inside_chroot(nsd.log_filename, nsd.chrootdir))			nsd.file_rotation_ok = 1;		/* strip chroot from pathnames if they're absolute */		nsd.options->zonesdir += l;		if (nsd.log_filename){			if (nsd.log_filename[0] == '/')				nsd.log_filename += l;		}		if (nsd.pidfile[0] == '/')			nsd.pidfile += l;		if (nsd.dbfile[0] == '/')			nsd.dbfile += l;		if (nsd.options->xfrdfile[0] == '/')			nsd.options->xfrdfile += l;		if (nsd.options->zonelistfile[0] == '/')			nsd.options->zonelistfile += l;		if (nsd.options->xfrdir[0] == '/')			nsd.options->xfrdir += l;		/* strip chroot from pathnames of "include:" statements		 * on subsequent repattern commands */		cfg_parser->chroot = nsd.chrootdir;#ifdef HAVE_TZSET		/* set timezone whilst not yet in chroot */		tzset();#endif		if (chroot(nsd.chrootdir)) {			error("unable to chroot: %s", strerror(errno));		}		if (chdir("/")) {			error("unable to chdir to chroot: %s", strerror(errno));		}		DEBUG(DEBUG_IPC,1, (LOG_INFO, "changed root directory to %s",			nsd.chrootdir));		/* chdir to zonesdir again after chroot */		if(nsd.options->zonesdir && nsd.options->zonesdir[0]) {			if(chdir(nsd.options->zonesdir)) {				error("unable to chdir to '%s': %s",					nsd.options->zonesdir, strerror(errno));			}			DEBUG(DEBUG_IPC,1, (LOG_INFO, "changed directory to %s",				nsd.options->zonesdir));		}	}	else#endif /* HAVE_CHROOT */		nsd.file_rotation_ok = 1;	DEBUG(DEBUG_IPC,1, (LOG_INFO, "file rotation on %s %sabled",		nsd.log_filename, nsd.file_rotation_ok?"en":"dis"));	/* Write pidfile */	if (writepid(&nsd) == -1) {		log_msg(LOG_ERR, "cannot overwrite the pidfile %s: %s",			nsd.pidfile, strerror(errno));	}
开发者ID:LTD-Beget,项目名称:nsd,代码行数:66,


示例18: main

/* * int * main(int argc, char **argv) *	Start routine of unc_dmctl command. */intmain(int argc, char **argv){	pfc_cmdopt_t	*parser;	cmdspec_t	*spec;	const char	*conffile = UNCD_CONF_PATH;	int		argidx, ret;	char		c;	/* Use C locale. */	(void)setlocale(LC_ALL, "C");	/* Set timezone. */	tzset();	/* Initialize signal. */	signal_init();	/* Create command line option parser. */	parser = pfc_cmdopt_init(PROGNAME, argc, argv, option_spec,				 arg_format, 0);	if (PFC_EXPECT_FALSE(parser == NULL)) {		fatal("Failed to create option parser.");		/* NOTREACHED */	}	while ((c = pfc_cmdopt_next(parser)) != PFC_CMDOPT_EOF) {		switch (c) {		case OPTCHAR_CONF:			conffile = pfc_cmdopt_arg_string(parser);			if (PFC_EXPECT_FALSE(*conffile == '/0')) {				fatal("Configuration file path is empty.");				/* NOTREACHED */			}			break;		case OPTCHAR_TIMEOUT:			ipc_timeout = pfc_cmdopt_arg_uint32(parser);			if (PFC_EXPECT_FALSE(ipc_timeout <					     IPC_TIMEOUT_MIN)) {				fatal("-%c: Timeout value must be greater than "				      "or equal %u.", OPTCHAR_TIMEOUT,				      IPC_TIMEOUT_MIN);				/* NOTREACHED */			}			else if (PFC_EXPECT_FALSE(ipc_timeout >						  IPC_TIMEOUT_MAX)) {				fatal("-%c: Timeout value must be less than "				      "or equal %u.", OPTCHAR_TIMEOUT,				      IPC_TIMEOUT_MAX);				/* NOTREACHED */			}			break;		case OPTCHAR_CHANNEL:			ipc_channel = pfc_cmdopt_arg_string(parser);			if (PFC_EXPECT_FALSE(*ipc_channel == '/0')) {				fatal("-%c: IPC channel name must not be "				      "empty.", OPTCHAR_CHANNEL);				/* NOTREACHED */			}			break;		case OPTCHAR_DEBUG:			debug_level++;			break;		case OPTCHAR_VERSION:			dump_version();			/* NOTREACHED */		case PFC_CMDOPT_USAGE:			pfc_cmdopt_usage(parser, stdout);			exit(DMCTL_EX_OK);			/* NOTREACHED */		case PFC_CMDOPT_HELP:			pfc_cmdopt_help(parser, stdout, HELP_MESSAGE);			exit(DMCTL_EX_OK);			/* NOTREACHED */		case PFC_CMDOPT_ERROR:			exit(DMCTL_EX_FATAL);			/* NOTREACHED */		default:			fatal("Failed to parse command line options.");			/* NOTREACHED */		}	}	if ((argidx = pfc_cmdopt_validate(parser)) == -1) {		fatal("Invalid command line options.");		/* NOTREACHED */	}//.........这里部分代码省略.........
开发者ID:KyongI,项目名称:cloudexchange,代码行数:101,


示例19: xml_amf_data_dump

//.........这里部分代码省略.........        }        /* print indentation spaces */        printf("%*s", indent_level * 2, "");        switch (data->type) {            case AMF_TYPE_NUMBER:                printf("<%snumber%s value=/"%.12g/"/>/n", ns, ns_decl, data->number_data);                break;            case AMF_TYPE_BOOLEAN:                printf("<%sboolean%s value=/"%s/"/>/n", ns, ns_decl, (data->boolean_data) ? "true" : "false");                break;            case AMF_TYPE_STRING:                if (amf_string_get_size(data) > 0) {                    printf("<%sstring%s>", ns, ns_decl);                    /* check whether the string contains xml characters, if so, CDATA it */                    markers = has_xml_markers((char*)amf_string_get_bytes(data), amf_string_get_size(data));                    if (markers) {                        printf("<![CDATA[");                    }                    /* do not print more than the actual length of string */                    printf("%.*s", (int)amf_string_get_size(data), amf_string_get_bytes(data));                    if (markers) {                        printf("]]>");                    }                    printf("</%sstring>/n", ns);                }                else {                    /* simplify empty xml element into a more compact form */                    printf("<%sstring%s/>/n", ns, ns_decl);                }                break;            case AMF_TYPE_OBJECT:                if (amf_object_size(data) > 0) {                    printf("<%sobject%s>/n", ns, ns_decl);                    node = amf_object_first(data);                    while (node != NULL) {                        printf("%*s<%sentry name=/"%s/">/n", (indent_level + 1) * 2, "", ns, amf_string_get_bytes(amf_object_get_name(node)));                        xml_amf_data_dump(amf_object_get_data(node), qualified, indent_level + 2);                        node = amf_object_next(node);                        printf("%*s</%sentry>/n", (indent_level + 1) * 2, "", ns);                    }                    printf("%*s</%sobject>/n", indent_level * 2, "", ns);                }                else {                    /* simplify empty xml element into a more compact form */                    printf("<%sobject%s/>/n", ns, ns_decl);                }                break;            case AMF_TYPE_NULL:                printf("<%snull%s/>/n", ns, ns_decl);                break;            case AMF_TYPE_UNDEFINED:                printf("<%sundefined%s/>/n", ns, ns_decl);                break;            case AMF_TYPE_ASSOCIATIVE_ARRAY:                if (amf_associative_array_size(data) > 0) {                    printf("<%sassociativeArray%s>/n", ns, ns_decl);                    node = amf_associative_array_first(data);                    while (node != NULL) {                        printf("%*s<%sentry name=/"%s/">/n", (indent_level + 1) * 2, "", ns, amf_string_get_bytes(amf_associative_array_get_name(node)));                        xml_amf_data_dump(amf_associative_array_get_data(node), qualified, indent_level + 2);                        node = amf_associative_array_next(node);                        printf("%*s</%sentry>/n", (indent_level + 1) * 2, "", ns);                    }                    printf("%*s</%sassociativeArray>/n", indent_level * 2, "", ns);                }                else {                    /* simplify empty xml element into a more compact form */                    printf("<%sassociativeArray%s/>/n", ns, ns_decl);                }                break;            case AMF_TYPE_ARRAY:                if (amf_array_size(data) > 0) {                    printf("<%sarray%s>/n", ns, ns_decl);                    node = amf_array_first(data);                    while (node != NULL) {                        xml_amf_data_dump(amf_array_get(node), qualified, indent_level + 1);                        node = amf_array_next(node);                    }                    printf("%*s</%sarray>/n", indent_level * 2, "", ns);                }                else {                    /* simplify empty xml element into a more compact form */                    printf("<%sarray%s/>/n", ns, ns_decl);                }                break;            case AMF_TYPE_DATE:                time = amf_date_to_time_t(data);                tzset();                t = localtime(&time);                strftime(datestr, sizeof(datestr), "%Y-%m-%dT%H:%M:%S", t);                printf("<%sdate%s value=/"%s/"/>/n", ns, ns_decl, datestr);                break;            case AMF_TYPE_XML: break;            case AMF_TYPE_CLASS: break;            default: break;        }    }}
开发者ID:bygreencn,项目名称:flvmeta,代码行数:101,


示例20: timegm

time_ttimegm (struct tm *tm){#ifdef HAVE_W32_SYSTEM  /* This one is thread safe.  */  SYSTEMTIME st;  FILETIME ft;  unsigned long long cnsecs;  st.wYear   = tm->tm_year + 1900;  st.wMonth  = tm->tm_mon  + 1;  st.wDay    = tm->tm_mday;  st.wHour   = tm->tm_hour;  st.wMinute = tm->tm_min;  st.wSecond = tm->tm_sec;  st.wMilliseconds = 0; /* Not available.  */  st.wDayOfWeek = 0;    /* Ignored.  */  /* System time is UTC thus the conversion is pretty easy.  */  if (!SystemTimeToFileTime (&st, &ft))    {      jnlib_set_errno (EINVAL);      return (time_t)(-1);    }  cnsecs = (((unsigned long long)ft.dwHighDateTime << 32)            | ft.dwLowDateTime);  cnsecs -= 116444736000000000ULL; /* The filetime epoch is 1601-01-01.  */  return (time_t)(cnsecs / 10000000ULL);#else /* (Non thread safe implementation!) */  time_t answer;  char *zone;  zone=getenv("TZ");  putenv("TZ=UTC");  tzset();  answer=mktime(tm);  if(zone)    {      static char *old_zone;      if (!old_zone)        {          old_zone = malloc(3+strlen(zone)+1);          if (old_zone)            {              strcpy(old_zone,"TZ=");              strcat(old_zone,zone);            }	}      if (old_zone)        putenv (old_zone);    }  else    gnupg_unsetenv("TZ");  tzset();  return answer;#endif}
开发者ID:FMayzek,项目名称:gnupg,代码行数:62,


示例21: main

//.........这里部分代码省略.........      else      {        fprintf(stderr, "cupsd: Child exited on signal %d/n", WTERMSIG(i));	return (3);      }    }#if defined(__OpenBSD__) && OpenBSD < 201211   /*    * Call _thread_sys_closefrom() so the child process doesn't reset the    * parent's file descriptors to be blocking.  This is a workaround for a    * limitation of userland libpthread on older versions of OpenBSD.    */    _thread_sys_closefrom(0);#endif /* __OpenBSD__ && OpenBSD < 201211 */   /*    * Since many system libraries create fork-unsafe data on execution of a    * program, we need to re-execute the background cupsd with the "-C" and "-s"    * options to avoid problems.  Unfortunately, we also have to assume that    * argv[0] contains the name of the cupsd executable - there is no portable    * way to get the real pathname...    */    execlp(argv[0], argv[0], "-C", ConfigurationFile, "-s", CupsFilesFile, (char *)0);    exit(errno);  } /*  * Set the timezone info...  */  tzset();#ifdef LC_TIME  setlocale(LC_TIME, "");#endif /* LC_TIME */#ifdef HAVE_DBUS_THREADS_INIT /*  * Enable threading support for D-BUS...  */  dbus_threads_init_default();#endif /* HAVE_DBUS_THREADS_INIT */ /*  * Set the maximum number of files...  */  getrlimit(RLIMIT_NOFILE, &limit);#if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)  if (limit.rlim_max > FD_SETSIZE)    MaxFDs = FD_SETSIZE;  else#endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */#ifdef RLIM_INFINITY  if (limit.rlim_max == RLIM_INFINITY)    MaxFDs = 16384;  else#endif /* RLIM_INFINITY */    MaxFDs = limit.rlim_max;  limit.rlim_cur = (rlim_t)MaxFDs;
开发者ID:apple,项目名称:cups,代码行数:67,


示例22: amf0_data_dump

/* dump AMF data into a stream as text */void amf0_data_dump(FILE * stream, const amf0_data *data, int indent_level) {    if (data != NULL) {        amf0_node * node;        time_t time;        struct tm * t;        char datestr[128];        switch (data->type) {            case AMF0_TYPE_NUMBER:                fprintf(stream, "%.12g", data->number_data);                break;            case AMF0_TYPE_BOOLEAN:                fprintf(stream, "%s", (data->boolean_data) ? "true" : "false");                break;            case AMF0_TYPE_STRING:                fprintf(stream, "/'%.*s/'", data->string_data.size, data->string_data.mbstr);                break;            case AMF0_TYPE_OBJECT:                node = amf0_object_first(data);                fprintf(stream, "{/n");                while (node != NULL) {                    fprintf(stream, "%*s", (indent_level+1)*4, "");                    amf0_data_dump(stream, amf0_object_get_name(node), indent_level+1);                    fprintf(stream, ": ");                    amf0_data_dump(stream, amf0_object_get_data(node), indent_level+1);                    node = amf0_object_next(node);                    fprintf(stream, "/n");                }                fprintf(stream, "%*s", indent_level*4 + 1, "}");                break;            case AMF0_TYPE_MOVIECLIP:                fprintf(stream, "[movieclip]");                break;            case AMF0_TYPE_NULL:                fprintf(stream, "null");                break;            case AMF0_TYPE_UNDEFINED:                fprintf(stream, "undefined");                break;            case AMF0_TYPE_REFERENCE: /* TODO */                fprintf(stream, "[reference]");                break;            case AMF0_TYPE_ECMA_ARRAY:                node = amf0_associative_array_first(data);                fprintf(stream, "{/n");                while (node != NULL) {                    fprintf(stream, "%*s", (indent_level+1)*4, "");                    amf0_data_dump(stream, amf0_associative_array_get_name(node), indent_level+1);                    fprintf(stream, " => ");                    amf0_data_dump(stream, amf0_associative_array_get_data(node), indent_level+1);                    node = amf0_associative_array_next(node);                    fprintf(stream, "/n");                }                fprintf(stream, "%*s", indent_level*4 + 1, "}");                break;            case AMF0_TYPE_OBJECT_END:                fprintf(stream, "[object end]");                break;            case AMF0_TYPE_STRICT_ARRAY:                node = amf0_array_first(data);                fprintf(stream, "[/n");                while (node != NULL) {                    fprintf(stream, "%*s", (indent_level+1)*4, "");                    amf0_data_dump(stream, node->data, indent_level+1);                    node = amf0_array_next(node);                    fprintf(stream, "/n");                }                fprintf(stream, "%*s", indent_level*4 + 1, "]");                break;            case AMF0_TYPE_DATE:                time = amf0_date_to_time_t(data);                tzset();                t = localtime(&time);                strftime(datestr, sizeof(datestr), "%a, %d %b %Y %H:%M:%S %z", t);                fprintf(stream, "%s", datestr);                break;            case AMF0_TYPE_LONG_STRING: /* TODO */                fprintf(stream, "[long string]");                break;            case AMF0_TYPE_UNSUPPORTED:                fprintf(stream, "[unsupported]");                break;            case AMF0_TYPE_RECORDSET:                fprintf(stream, "[recordset]");                break;            case AMF0_TYPE_XML_DOCUMENT: /* TODO */                fprintf(stream, "[xml document]");                break;            case AMF0_TYPE_TYPED_OBJECT: /* TODO */                fprintf(stream, "[typed object]");                break;            default:                fprintf(stream, "[unknown data type 0x%x]", data->type);                break;        }    }}
开发者ID:xuyetao1351552,项目名称:libamf,代码行数:97,


示例23: date_parse

time_t date_parse(const char *str){    time_t now;    struct tm* now_tmP;    struct tm tm;    const char* cp;    char str_mon[500], str_wday[500], str_gmtoff[500], str_ampm[500];    int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday, gmtoff, local_gmtoff;    int ampm, got_zone;    time_t t;    if (!str || !*str) return (time_t) 0;    /* Initialize tm with relevant parts of current local time. */    now = time( (time_t*) 0 );    now_tmP = localtime( &now );    bzero( (char*) &tm, sizeof(struct tm) );    tm.tm_sec = now_tmP->tm_sec;    tm.tm_min = now_tmP->tm_min;    tm.tm_hour = now_tmP->tm_hour;    tm.tm_mday = now_tmP->tm_mday;    tm.tm_mon = now_tmP->tm_mon;    tm.tm_year = now_tmP->tm_year;    ampm = AMPM_NONE;    got_zone = 0;    /* Find local zone offset.  This is the only real area of    ** non-portability, and it's only used for local times that don't    ** specify a zone - those don't occur in email and netnews.    */#ifdef HAVE_STRUCT_TM_GMTOFF    gmtoff = now_tmP->tm_gmtoff;#else    tzset();    gmtoff = -timezone;#endif	local_gmtoff = gmtoff;    /* Skip initial whitespace ourselves - sscanf is clumsy at this. */    for ( cp = str; *cp == ' ' || *cp == '/t'; ++cp )	;    /* And do the sscanfs.  WARNING: you can add more formats here,    ** but be careful!  You can easily screw up the parsing of existing    ** formats when you add new ones.    */    /* N mth YYYY HH:MM:SS ampm zone */    if ( ( ( sscanf( cp, "%d %[a-zA-Z] %d %d:%d:%d %[apmAPM] %[^: ]",		&tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, &tm_sec, str_ampm, str_gmtoff ) == 8 &&	    scan_ampm( str_ampm, &ampm ) ) ||            sscanf( cp, "%d %[a-zA-Z] %d %d:%d:%d %[^: ]",		&tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, &tm_sec, str_gmtoff ) == 7 ) &&	    scan_mon( str_mon, &tm_mon ) &&	    scan_gmtoff( str_gmtoff, &gmtoff ) )	{	DP( "N mth YYYY HH:MM:SS ampm zone" );	tm.tm_mday = tm_mday;	tm.tm_mon = tm_mon;	tm.tm_year = tm_year;	tm.tm_hour = ampm_fix( tm_hour, ampm );	tm.tm_min = tm_min;	tm.tm_sec = tm_sec;	got_zone = 1;	}    /* N mth YYYY HH:MM ampm zone */    else if ( ( ( sscanf( cp, "%d %[a-zA-Z] %d %d:%d %[apmAPM] %[^: ]",		&tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, str_ampm, str_gmtoff ) == 7 &&	    scan_ampm( str_ampm, &ampm ) ) ||            sscanf( cp, "%d %[a-zA-Z] %d %d:%d %[^: ]",		&tm_mday, str_mon, &tm_year, &tm_hour, &tm_min,	str_gmtoff ) == 6 ) &&	    scan_mon( str_mon, &tm_mon ) &&	    scan_gmtoff( str_gmtoff, &gmtoff ) )	{	DP( "N mth YYYY HH:MM ampm zone" );	tm.tm_mday = tm_mday;	tm.tm_mon = tm_mon;	tm.tm_year = tm_year;	tm.tm_hour = ampm_fix( tm_hour, ampm );	tm.tm_min = tm_min;	tm.tm_sec = 0;	got_zone = 1;	}    /* N mth YYYY HH:MM:SS ampm */    else if ( ( ( sscanf( cp, "%d %[a-zA-Z] %d %d:%d:%d %[apmAPM]",		&tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, &tm_sec, str_ampm ) == 7 &&	    scan_ampm( str_ampm, &ampm ) ) ||            sscanf( cp, "%d %[a-zA-Z] %d %d:%d:%d",		&tm_mday, str_mon, &tm_year, &tm_hour, &tm_min,	&tm_sec ) == 6 ) &&	    scan_mon( str_mon, &tm_mon ) )	{	DP( "N mth YYYY HH:MM:SS ampm" );	tm.tm_mday = tm_mday;	tm.tm_mon = tm_mon;	tm.tm_year = tm_year;	tm.tm_hour = ampm_fix( tm_hour, ampm );	tm.tm_min = tm_min;//.........这里部分代码省略.........
开发者ID:1029384756wait,项目名称:smx,代码行数:101,


示例24: print_status_info

static void print_status_info(const StatusInfo *i) {        const char *old_tz = NULL, *tz;        bool have_time = false;        char a[LINE_MAX];        struct tm tm;        time_t sec;        size_t n;        int r;        assert(i);        /* Save the old $TZ */        tz = getenv("TZ");        if (tz)                old_tz = strdupa(tz);        /* Set the new $TZ */        if (setenv("TZ", isempty(i->timezone) ? "UTC" : i->timezone, true) < 0)                log_warning_errno(errno, "Failed to set TZ environment variable, ignoring: %m");        else                tzset();        if (i->time != 0) {                sec = (time_t) (i->time / USEC_PER_SEC);                have_time = true;        } else if (IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE)) {                sec = time(NULL);                have_time = true;        } else                log_warning("Could not get time from timedated and not operating locally, ignoring.");        if (have_time) {                n = strftime(a, sizeof a, "%a %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm));                printf("               Local time: %s/n", n > 0 ? a : "n/a");                n = strftime(a, sizeof a, "%a %Y-%m-%d %H:%M:%S UTC", gmtime_r(&sec, &tm));                printf("           Universal time: %s/n", n > 0 ? a : "n/a");        } else {                printf("               Local time: %s/n", "n/a");                printf("           Universal time: %s/n", "n/a");        }        if (i->rtc_time > 0) {                time_t rtc_sec;                rtc_sec = (time_t) (i->rtc_time / USEC_PER_SEC);                n = strftime(a, sizeof a, "%a %Y-%m-%d %H:%M:%S", gmtime_r(&rtc_sec, &tm));                printf("                 RTC time: %s/n", n > 0 ? a : "n/a");        } else                printf("                 RTC time: %s/n", "n/a");        if (have_time)                n = strftime(a, sizeof a, "%Z, %z", localtime_r(&sec, &tm));        /* Restore the $TZ */        if (old_tz)                r = setenv("TZ", old_tz, true);        else                r = unsetenv("TZ");        if (r < 0)                log_warning_errno(errno, "Failed to set TZ environment variable, ignoring: %m");        else                tzset();        printf("                Time zone: %s (%s)/n"               "System clock synchronized: %s/n"               "              NTP service: %s/n"               "          RTC in local TZ: %s/n",               strna(i->timezone), have_time && n > 0 ? a : "n/a",               yes_no(i->ntp_synced),               i->ntp_capable ? (i->ntp_active ? "active" : "inactive") : "n/a",               yes_no(i->rtc_local));        if (i->rtc_local)                printf("/n%s"                       "Warning: The system is configured to read the RTC time in the local time zone./n"                       "         This mode cannot be fully supported. It will create various problems/n"                       "         with time zone changes and daylight saving time adjustments. The RTC/n"                       "         time is never updated, it relies on external facilities to maintain it./n"                       "         If at all possible, use RTC in UTC by calling/n"                       "         'timedatectl set-local-rtc 0'.%s/n", ansi_highlight(), ansi_normal());}
开发者ID:iamyooon,项目名称:systemd,代码行数:82,


示例25: main

intmain(int argc, char **argv){  int c;  int forkaway = 0;  FILE *pidfile;  const char *pidpath = "/var/run/tvheadend.pid";  struct group *grp;  struct passwd *pw;  const char *usernam = NULL;  const char *groupnam = NULL;  int logfacility = LOG_DAEMON;  int createdefault = 0;  sigset_t set;  const char *homedir;  const char *rawts_input = NULL;#if ENABLE_LINUXDVB  const char *dvb_rawts_input = NULL;#endif  const char *join_transport = NULL;  const char *confpath = NULL;  char *p, *endp;  uint32_t adapter_mask = 0xffffffff;  int crash = 0;  webui_port = 9981;  htsp_port = 9982;  gid_t gid;  uid_t uid;  /* Get current directory */  tvheadend_cwd = dirname(dirname(tvh_strdupa(argv[0])));  /* Set locale */  setlocale(LC_ALL, "");  // make sure the timezone is set  tzset();  while((c = getopt(argc, argv, "Aa:fp:u:g:c:Chdr:j:sw:e:E:R:W:")) != -1) {    switch(c) {    case 'a':      adapter_mask = 0x0;      p = strtok(optarg, ",");      if (p != NULL) {        do {          int adapter = strtol(p, &endp, 10);          if (*endp != 0 || adapter < 0 || adapter > 31) {              fprintf(stderr, "Invalid adapter number '%s'/n", p);              return 1;          }          adapter_mask |= (1 << adapter);        } while ((p = strtok(NULL, ",")) != NULL);        if (adapter_mask == 0x0) {          fprintf(stderr, "No adapters specified!/n");          return 1;        }      } else {        usage(argv[0]);      }      break;    case 'A':      crash = 1;      break;    case 'f':      forkaway = 1;      break;    case 'p':      pidpath = optarg;      break;    case 'w':      webui_port = atoi(optarg);      break;    case 'e':      htsp_port = atoi(optarg);      break;    case 'E':      htsp_port_extra = atoi(optarg);      break;    case 'u':      usernam = optarg;      break;    case 'g':      groupnam = optarg;      break;    case 'c':      confpath = optarg;      break;    case 'd':      log_debug_to_console = 1;      break;    case 's':      log_debug_to_syslog = 1;      break;    case 'C':      createdefault = 1;      break;    case 'r':      rawts_input = optarg;      break;#if ENABLE_LINUXDVB//.........这里部分代码省略.........
开发者ID:PiratJones,项目名称:tvheadend,代码行数:101,


示例26: Init_openssl

//.........这里部分代码省略......... *   puts ssl_client.gets * * === Peer Verification * * An unverified SSL connection does not provide much security.  For enhanced * security the client or server can verify the certificate of its peer. * * The client can be modified to verify the server's certificate against the * certificate authority's certificate: * *   context.ca_file = 'ca_cert.pem' *   context.verify_mode = OpenSSL::SSL::VERIFY_PEER * *   require 'socket' * *   tcp_client = TCPSocket.new 'localhost', 5000 *   ssl_client = OpenSSL::SSL::SSLSocket.new client_socket, context *   ssl_client.connect * *   ssl_client.puts "hello server!" *   puts ssl_client.gets * * If the server certificate is invalid or <tt>context.ca_file</tt> is not set * when verifying peers an OpenSSL::SSL::SSLError will be raised. * */voidInit_openssl(){    /*     * Init timezone info     */#if 0    tzset();#endif    /*     * Init all digests, ciphers     */    /* CRYPTO_malloc_init(); */    /* ENGINE_load_builtin_engines(); */    OpenSSL_add_ssl_algorithms();    OpenSSL_add_all_algorithms();    ERR_load_crypto_strings();    SSL_load_error_strings();    /*     * FIXME:     * On unload do:     */#if 0    CONF_modules_unload(1);    destroy_ui_method();    EVP_cleanup();    ENGINE_cleanup();    CRYPTO_cleanup_all_ex_data();    ERR_remove_state(0);    ERR_free_strings();#endif    /*     * Init main module     */    mOSSL = rb_define_module("OpenSSL");    /*
开发者ID:SongJungHwan,项目名称:hwan,代码行数:67,


示例27: main

//.........这里部分代码省略.........#endif    {   0, "uidebug",   N_("Enable web UI debug (non-minified JS)"), OPT_BOOL, &opt_uidebug },    { 'A', "abort",     N_("Immediately abort"),       OPT_BOOL, &opt_abort   },    { 'D', "dump",      N_("Enable coredumps for daemon"), OPT_BOOL, &opt_dump },    {   0, "noacl",     N_("Disable all access control checks"),      OPT_BOOL, &opt_noacl },    {   0, "nobat",     N_("Disable DVB bouquets"),      OPT_BOOL, &opt_nobat },    { 'j', "join",      N_("Subscribe to a service permanently"),      OPT_STR, &opt_subscribe },#if ENABLE_TSFILE || ENABLE_TSDEBUG    { 0, NULL, N_("Testing options"), OPT_BOOL, NULL },    { 0, "tsfile_tuners", N_("Number of tsfile tuners"), OPT_INT, &opt_tsfile_tuner },    { 0, "tsfile", N_("tsfile input (mux file)"), OPT_STR_LIST, &opt_tsfile },#endif#if ENABLE_TSDEBUG    { 0, "tsdebug", N_("Output directory for tsdebug"), OPT_STR, &tvheadend_tsdebug },#endif  };  /* Get current directory */  tvheadend_cwd0 = dirname(tvh_strdupa(argv[0]));  tvheadend_cwd = dirname(tvh_strdupa(tvheadend_cwd0));  /* Set locale */  setlocale(LC_ALL, "");  setlocale(LC_NUMERIC, "C");  tvh_gettext_init();  /* make sure the timezone is set */  tzset();  /* Process command line */  for (i = 1; i < argc; i++) {    /* Find option */    cmdline_opt_t *opt      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);    if (!opt) {      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),                 _("invalid option specified [%s]"), argv[i]);      continue;    }    /* Process */    if (opt->type == OPT_BOOL)      *((int*)opt->param) = 1;    else if (++i == argc)      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),                 _("option %s requires a value"), opt->lopt);    else if (opt->type == OPT_INT)      *((int*)opt->param) = atoi(argv[i]);    else if (opt->type == OPT_STR_LIST) {      str_list_t *strl = opt->param;      if (strl->num < strl->max)        strl->str[strl->num++] = argv[i];    }    else      *((char**)opt->param) = argv[i];    /* Stop processing */    if (opt_help)      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
开发者ID:Ferni7,项目名称:tvheadend,代码行数:67,


示例28: event_server_main

//.........这里部分代码省略.........     * Illustrated volume 2 page 532. We avoid select() collisions with an     * external lock file.     */    /*     * XXX Can't compete for exclusive access to the listen socket because we     * also have to monitor existing client connections for service requests.     */#if 0    if (stream == 0 && !alone) {	lock_path = concatenate(DEF_PID_DIR, "/", transport,				".", service_name, (char *) 0);	why = vstring_alloc(1);	if ((event_server_lock = safe_open(lock_path, O_CREAT | O_RDWR, 0600,				      (struct stat *) 0, -1, -1, why)) == 0)	    msg_fatal("open lock file %s: %s", lock_path, vstring_str(why));	close_on_exec(vstream_fileno(event_server_lock), CLOSE_ON_EXEC);	myfree(lock_path);	vstring_free(why);    }#endif    /*     * Set up call-back info.     */    event_server_service = service;    event_server_name = service_name;    event_server_argv = argv + optind;    /*     * Run pre-jail initialization.     */    if (chdir(var_queue_dir) < 0)	msg_fatal("chdir(/"%s/"): %m", var_queue_dir);    if (pre_init)	pre_init(event_server_name, event_server_argv);    /*     * Optionally, restrict the damage that this process can do.     */    resolve_local_init();    tzset();    chroot_uid(root_dir, user_name);    /*     * Run post-jail initialization.     */    if (post_init)	post_init(event_server_name, event_server_argv);    /*     * Are we running as a one-shot server with the client connection on     * standard input? If so, make sure the output is written to stdout so as     * to satisfy common expectation.     */    if (stream != 0) {	vstream_control(stream,			VSTREAM_CTL_DOUBLE,			VSTREAM_CTL_WRITE_FD, STDOUT_FILENO,			VSTREAM_CTL_END);	service(stream, event_server_name, event_server_argv);	vstream_fflush(stream);	event_server_exit();    }    /*     * Running as a semi-resident server. Service connection requests.     * Terminate when we have serviced a sufficient number of clients, when     * no-one has been talking to us for a configurable amount of time, or     * when the master process terminated abnormally.     */    if (var_idle_limit > 0)	event_request_timer(event_server_timeout, (char *) 0, var_idle_limit);    for (fd = MASTER_LISTEN_FD; fd < MASTER_LISTEN_FD + socket_count; fd++) {	event_enable_read(fd, event_server_accept, CAST_INT_TO_CHAR_PTR(fd));	close_on_exec(fd, CLOSE_ON_EXEC);    }    event_enable_read(MASTER_STATUS_FD, event_server_abort, (char *) 0);    close_on_exec(MASTER_STATUS_FD, CLOSE_ON_EXEC);    close_on_exec(MASTER_FLOW_READ, CLOSE_ON_EXEC);    close_on_exec(MASTER_FLOW_WRITE, CLOSE_ON_EXEC);    watchdog = watchdog_create(event_server_watchdog,			       (WATCHDOG_FN) 0, (char *) 0);    /*     * The event loop, at last.     */    while (var_use_limit == 0 || use_count < var_use_limit || client_count > 0) {	if (event_server_lock != 0) {	    watchdog_stop(watchdog);	    if (myflock(vstream_fileno(event_server_lock), INTERNAL_LOCK,			MYFLOCK_OP_EXCLUSIVE) < 0)		msg_fatal("select lock: %m");	}	watchdog_start(watchdog);	delay = loop ? loop(event_server_name, event_server_argv) : -1;	event_loop(delay);    }    event_server_exit();}
开发者ID:ajinkya93,项目名称:netbsd-src,代码行数:101,


示例29: read_request

//.........这里部分代码省略.........        if ( fd<0 )        {            process->response_code = 404;            process->status = STATUS_SEND_RESPONSE_HEADER;            strcpy ( process->buf, header_404 );            send_response_header ( process );            handle_error ( processes, "not found" );            return;        }        else        {            process->response_code = 200;        }	        char tempstring[256];        //检查有无If-Modified-Since,返回304        char* c = strstr ( buf, HEADER_IF_MODIFIED_SINCE );	if(c!=0){	    char* rn = strchr(c, '/r');	    if(rn==0){	      rn = strchr(c, '/n');	      if(rn==0){		  process->response_code = 400;		  process->status = STATUS_SEND_RESPONSE_HEADER;		  strcpy ( process->buf, header_400 );		  send_response_header ( process );		  handle_error ( processes, "bad request" );		  return;	      }	    }	  int time_len = rn - c - sizeof(HEADER_IF_MODIFIED_SINCE) + 1;	  strncpy(tempstring, c + sizeof(HEADER_IF_MODIFIED_SINCE) - 1,time_len);	  tempstring[time_len]=0;	  {	    struct tm tm;	    time_t t;	    strptime(tempstring, RFC1123_DATE_FMT, &tm);	    tzset();	    t=mktime(&tm);	    t-=timezone;	    gmtime_r(&t, &tm);	    if(t >= filestat.st_mtime){	      process->response_code = 304;	    }	  }	}        //开始header        process->buf[0] = 0;	if(process->response_code == 304){	  write_to_header ( header_304_start );	} else {	  write_to_header ( header_200_start );	}        process->total_length = filestat.st_size;	{	  //写入当前时间	  struct tm *tm;	  time_t tmt;	  tmt = time ( NULL );	  tm = gmtime ( &tmt );	  strftime ( tempstring, sizeof ( tempstring ), RFC1123_DATE_FMT, tm );	  write_to_header ( "Date: " );	  write_to_header ( tempstring );	  write_to_header ( "/r/n" );	  //写入文件修改时间	  tm = gmtime ( &filestat.st_mtime );	  strftime ( tempstring, sizeof ( tempstring ), RFC1123_DATE_FMT, tm );	  write_to_header ( "Last-modified: " );	  write_to_header ( tempstring );	  write_to_header ( "/r/n" );	  if(process->response_code == 200){	    //写入content长度	    sprintf ( tempstring, "Content-Length: %ld/r/n", filestat.st_size );	    write_to_header ( tempstring );	  }	}        //结束header        write_to_header ( header_end );        process->status = STATUS_SEND_RESPONSE_HEADER;        //修改此sock的监听状态,改为监视写状态        event.data.fd = process->sock;        event.events = EPOLLOUT | EPOLLET;        s = epoll_ctl ( efd, EPOLL_CTL_MOD, process->sock, &event );        if ( s == -1 )        {            perror ( "epoll_ctl" );            abort ();        }        //发送header        send_response_header ( process );    }}
开发者ID:SylvanHuang,项目名称:clowwindy_server,代码行数:101,



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


C++ u函数代码示例
C++ typemask函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。