static void settime(cell hour,cell minute,cell second) { #if defined __WIN32__ || defined _WIN32 || defined WIN32 SYSTEMTIME systim; GetLocalTime(&systim); if (hour!=CELLMIN) systim.wHour=(WORD)wrap((int)hour,0,23); if (minute!=CELLMIN) systim.wMinute=(WORD)wrap((int)minute,0,59); if (second!=CELLMIN) systim.wSecond=(WORD)wrap((int)second,0,59); SetLocalTime(&systim); #else /* Linux/Unix (and some DOS compilers) have stime(); on Linux/Unix, you * must have "root" permission to call stime() */ time_t sec1970; struct tm gtm; time(&sec1970); gtm=*localtime(&sec1970); if (hour!=CELLMIN) gtm.tm_hour=wrap((int)hour,0,23); if (minute!=CELLMIN) gtm.tm_min=wrap((int)minute,0,59); if (second!=CELLMIN) gtm.tm_sec=wrap((int)second,0,59); sec1970=mktime(>m); stime(&sec1970); #endif }
/****************************************************************************** * version: 1.0 * author: link * date: 2015.11.10 * brief: 设置系统时间 ******************************************************************************/ int LINUX_RTC::set_rtc(rtc_time rtc_tm) { int ret; int rtc_fd; time_t t1; rtc_tm.tm_year -= 1900; //年从1900开始 rtc_tm.tm_mon -= 1; //月从0开始 rtc_fd = open("/dev/rtc0", O_RDWR, 0); //打开RTC if (rtc_fd == -1){ printf("/dev/rtc0 open error\n"); return -1; } t1 = timelocal((tm*)&rtc_tm); //设置系统时间 stime(&t1); ret = ioctl(rtc_fd, RTC_SET_TIME, &rtc_tm); //设置RTC时间 if (ret == -1){ printf("rtc ioctl RTC_SET_TIME error\r\n"); return -1; } close(rtc_fd); //关闭RTC return 0; }
int settime (struct timespec const *ts) { #if defined CLOCK_REALTIME && HAVE_CLOCK_SETTIME { int r = clock_settime (CLOCK_REALTIME, ts); if (r == 0 || errno == EPERM) return r; } #endif #if HAVE_SETTIMEOFDAY { struct timeval tv; tv.tv_sec = ts->tv_sec; tv.tv_usec = ts->tv_nsec / 1000; return settimeofday (&tv, 0); } #elif HAVE_STIME /* This fails to compile on OSF1 V5.1, due to stime requiring a `long int*' and tv_sec is `int'. But that system does provide settimeofday. */ return stime (&ts->tv_sec); #else errno = ENOSYS; return -1; #endif }
/* settimestamp(seconds1970) sets the date and time from a single parameter: the * number of seconds since 1 January 1970. */ static cell AMX_NATIVE_CALL n_settimestamp(AMX *amx, const cell *params) { #if defined __WIN32__ || defined _WIN32 || defined WIN32 int year, month, day, hour, minute, second; stamp2datetime(params[1], &year, &month, &day, &hour, &minute, &second); setdate(year, month, day); settime(hour, minute, second); #else /* Linux/Unix (and some DOS compilers) have stime(); on Linux/Unix, you * must have "root" permission to call stime(); many POSIX systems will * have settimeofday() instead */ #if defined __APPLE__ /* also valid for other POSIX systems */ struct timeval tv; tv.tv_sec = params[1]; tv.tv_usec = 0; settimeofday(&tv, 0); #else time_t sec1970=(time_t)params[1]; stime(&sec1970); #endif #endif (void)amx; return 0; }
int Dij(int st,int en){ memset(f,-1,sizeof(f)); memset(tag,0,sizeof(tag)); int i,j,k,ll,p; f[st]=0;h[st]=0; for (ll=0;ll<n;ll++){ p=-1; for (i=1;i<=n;i++) if (f[i]>-1 && !tag[i]) if (p==-1 || f[i]<f[p]) p=i; if (p==-1) break; tag[p]=1; for (j=0;j<gn[p];j++){ k=g[p][j]; int time=stime(p,k,f[p])+d[p][k]; if (time<0) continue; if (f[k]==-1 || time<f[k]){ f[k]=time; h[k]=p; } } } if (f[en]==-1) return 0; printf("%d\n",f[en]); pr(en); printf("\n"); return 1; }
int main(int argc, char *argv[]){ int descritor; time_t horaLocal, horaRemota; /* FIXME A validação está atrelada a uma regex que considera alguns valores inválidos * como válidos */ if(argc != 3 || !validaParametros(argv[1], (int)strtol(argv[2], (char **)NULL, 10))){ fprintf(stderr, "Uso: %s <ip> <porta>\n", argv[0]); exit(1); } descritor = conectaAServidorTCP(argv[1], (int)strtol(argv[2], (char **)NULL, 10)); horaLocal = time(NULL); horaRemota=recebeHora(descritor); /* ctime imprime uma variável time_t em forma amigável, como na saída do comando date */ printf("Timestamp recebido de %s:%d --> %ld = %s", argv[1], atoi(argv[2]), horaRemota, ctime(&horaRemota)); printf("Timestamp local --> %ld = %s\n", horaLocal, ctime(&horaLocal)); /* difftime retorna a diferença entre dois timestamps (time_t) em segundos */ printf("Diferença (remoto-local) entre data/hora local e remota (em segundos): %.0f\n", difftime(horaRemota, horaLocal)); /* stime recebe um ponteiro para time_t e atualiza o relógio do sistema com seu valor */ if(stime(&horaRemota)!=0){ fprintf(stderr, "A hora não foi alterada. Você é root?\n"); fechaDescritores(); exit(1); } fechaDescritores(); }
void XLibStatusWindow::drawClock() { time_t rawtime; tm *timeinfo; // format time time(&rawtime); timeinfo = localtime(&rawtime); std::string stime(asctime(timeinfo)); // get the string (pixels used to draw) size size s = _xft->getStringSize(stime); // 'clear' the screen drawing the string. XClearArea(_display.get(), window(), width() - s.width - 5, 0, width(), height(), False); // draws the status bar in the window. _xft->drawString(GREEN, width() - s.width, height() - 5, stime); }
static void storage_load_time(void) { FILE *fp; char buf[32]; struct tm storage_tm; time_t storage_time = 0; if (nvram_match("stime_stored", "0")) return; fp = fopen("/etc/storage/system_time", "r"); if (fp) { if (fgets(buf, sizeof(buf), fp)) storage_time = (time_t)strtoul(buf, NULL, 0); fclose(fp); } if (storage_time > 0) { localtime_r(&storage_time, &storage_tm); if (storage_tm.tm_year > (SYS_START_YEAR - 1900)) { storage_time = mktime(&storage_tm); storage_time += 5; // add delta 5 sec (~boot time) stime(&storage_time); } } }
cTDT::cTDT(const u_char *Data) :SI::TDT(Data, false) { CheckParse(); time_t sattim = getTime(); time_t loctim = time(NULL); int diff = abs(sattim - loctim); if (diff > 2) { mutex.Lock(); if (abs(diff - lastDiff) < 3) { isyslog("System Time = %s (%ld)", *TimeToString(loctim), loctim); isyslog("Local Time = %s (%ld)", *TimeToString(sattim), sattim); if (stime(&sattim) < 0){ char __errorstr[256]; strerror_r(errno,__errorstr,256); __errorstr[255]=0; esyslog("ERROR while setting system time: %s",__errorstr); } } lastDiff = diff; mutex.Unlock(); } }
int rdate_main(int argc UNUSED_PARAM, char **argv) { time_t remote_time; unsigned long flags; opt_complementary = "-1"; flags = getopt32(argv, "sp"); remote_time = askremotedate(argv[optind]); if ((flags & 2) == 0) { time_t current_time; time(¤t_time); if (current_time == remote_time) bb_error_msg("current time matches remote time"); else if (stime(&remote_time) < 0) bb_perror_msg_and_die("can't set time of day"); } if ((flags & 1) == 0) printf("%s", ctime(&remote_time)); return EXIT_SUCCESS; }
int stime32(time32_t time) { if (time < 0) return (set_errno(EINVAL)); return (stime((time_t)time)); }
int settimeofday(const struct timeval *tp, const void *tzp) { /* Use intermediate variable because stime param is not const */ time_t sec = tp->tv_sec; /* Ignore time zones */ return stime(&sec); }
int main(int argc, char *argv[]) { register char *tzn; struct timeb info; int wf, rc; rc = 0; ftime(&info); if (argc>1 && argv[1][0]=='-' && argv[1][1]=='u') { argc--; argv++; uflag++; } if(argc > 1) { ap = argv[1]; if (gtime()) { printf("date: bad conversion\n"); exit(1); } /* convert to GMT assuming local time */ if (uflag==0) { timbuf += (long)info.timezone*60; /* now fix up local daylight time */ if(localtime(&timbuf)->tm_isdst) timbuf -= 60*60; } time(&timevalue); wtmp[0].ut_time = timevalue; if(stime(&timbuf) < 0) { rc++; printf("date: no permission\n"); // TODO: check! } else if ((wf = open("/usr/adm/wtmp", O_WRONLY|O_CREAT|O_APPEND)) >= 0) { wtmp[1].ut_time = timevalue; //lseek(wf, 0L, 2); write(wf, (char *)wtmp, sizeof(wtmp)); close(wf); } } if (rc==0) time(&timbuf); if(uflag) { ap = asctime(gmtime(&timbuf)); tzn = "GMT"; } else { struct tm *tp; tp = localtime(&timbuf); ap = asctime(tp); tzn = timezone(info.timezone, tp->tm_isdst); } printf("%.20s", ap); if (tzn) printf("%s", tzn); printf("%s", ap+19); exit(rc); }
void Monitor::CalculateNextRunTime(CTime time) { m_LastRunTime=time; CTimeSpan stime(0,0,m_Frequency,0); m_NextRunTime=time; m_NextRunTime+=stime; }
int main(int argc, char** argv){ struct timeval tv; if(argc > 4 || parseargs(argc, argv) == 0) return -1; /* This starts the xuartctl daemon TODO - Should we start it */ /* printf("Starting xuartctl...");*/ /* fflush(stdout);*/ /* system("xuartctl -d -p 0 -o 8n1 -s 9600");*/ /* printf("done\n");*/ printf("Starting gps with device %s\n", gps_device); uart_init( 0, stderr, gps_device); original_tries = tries; for(;!is_gps_ready(); tries--) { if(tries <= 0) { fprintf(stderr, "Number of tries limit of %u was reached. Returning error -1\n", original_tries); return -1; } sleep(1); } printf("GPS is ready. Reading value and setting it in kernel.\n"); switch(getGPStimeUTC(&tv)){ case 1: fprintf(stderr, "Unable to read time from GPS (Error 1)\n"); return -1; case 2: fprintf(stderr, "An error occured while waiting for a time reply (Error 2)\n"); return -1; } printf("GPS returned with UNIX seconds: %ld\n", tv.tv_sec); // set miavita time set_seconds((uint64_t) tv.tv_sec); /* Set's the seconds in the miavia counter in the kernel cat ts7500_kernel/ipc/miavita_syscall.c:sys_miavitasetseconds */ printf("Seconds set in the miavita kernel variable: %lu\n", get_mean_value()); printf("Now I'm going to set the current date to the OS\n"); printf("Time at before setting:\n"); print_time(); // set system time time_t seconds_time = (time_t) tv.tv_sec; stime(&seconds_time); sleep(2); printf("Time at after setting:\n"); print_time(); printf("Program finished without errors.\n"); return 0; }
int rdate_main(int argc, char **argv) { time_t remote_time; struct tm *p; int opt; int setdate = 1; int printdate = 1; int setzone = 1; int zone = 0; /* Interpret command line args */ while ((opt = getopt(argc, argv, "spz:")) > 0) { switch (opt) { case 's': printdate = 0; setdate = 1; setzone = 0; break; case 'p': printdate = 1; setdate = 0; setzone = 0; break; case 'z': printdate = 0; setdate = 1; setzone = 1; zone = atoi(optarg); break; default: bb_show_usage(); } } if (optind == argc) bb_show_usage(); remote_time = askremotedate(argv[optind]); if (setdate) { if(setzone) { p=localtime(&remote_time); p->tm_hour += zone; remote_time=mktime(p); } if (stime(&remote_time) < 0) bb_perror_msg_and_die("Could not set time of day"); } if (printdate) printf("%s", ctime(&remote_time)); return EXIT_SUCCESS; }
int ENT3F(STIME, stime)(int *tp) { int i; time_t t = *tp; if ((i = stime(&t))) i = __io_errno(); return i; }
void set_local_time(char *buf) { time_t t; t=string_to_uint(buf); //printf("I get %s %d\n",buf,strlen(buf)); //printf("%u\n",(unsigned)t); stime(&t); printf("%s\n",ctime(&t)); printf("Set Time Successed. . .\n"); }
int _set_sys_time(time_t _time) { struct tm *_tm; struct tm result; _tm = gmtime_r(&_time, &result); stime(&_time); return 1; }
void start_sysinit(void) { char buf[PATH_MAX]; struct stat tmp_stat; time_t tm = 0; if (!nvram_match("disable_watchdog", "1")) eval("watchdog"); /* * Setup console */ cprintf("sysinit() klogctl\n"); klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel"))); cprintf("sysinit() get router\n"); int brand = getRouterBrand(); /* * network drivers */ insmod("ag7100_mod"); int s; struct ifreq ifr; if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))) { char eabuf[32]; strncpy(ifr.ifr_name, "eth0", IFNAMSIZ); ioctl(s, SIOCGIFHWADDR, &ifr); char macaddr[32]; strcpy(macaddr, ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf)); nvram_set("et0macaddr", macaddr); nvram_set("et0macaddr_safe", macaddr); close(s); } #ifdef HAVE_MADWIFI_MIMO // insmod("ath_pci", "autocreate=none"); insmod("ath_mimo_pci"); #endif // eval ("ifconfig", "wifi0", "up"); /* * Set a sane date */ stime(&tm); nvram_set("wl0_ifname", "ath0"); return; cprintf("done\n"); }
void start_sysinit(void) { char buf[PATH_MAX]; struct stat tmp_stat; time_t tm = 0; eval("/bin/tar", "-xzf", "/dev/mtdblock/2", "-C", "/"); FILE *in = fopen("/tmp/nvram/nvram.db", "rb"); if (in != NULL) { fclose(in); eval("/usr/sbin/convertnvram"); eval("/sbin/mtd", "erase", "nvram"); nvram_commit(); } if (!nvram_match("disable_watchdog", "1")) eval("watchdog"); /* * Setup console */ cprintf("sysinit() klogctl\n"); klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel"))); cprintf("sysinit() get router\n"); int brand = getRouterBrand(); /* * network drivers */ detect_wireless_devices(); struct ifreq ifr; int s; if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))) { char eabuf[32]; strncpy(ifr.ifr_name, "eth0", IFNAMSIZ); ioctl(s, SIOCGIFHWADDR, &ifr); nvram_set("et0macaddr_safe", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf)); nvram_set("et0macaddr", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf)); close(s); } /* * Set a sane date */ stime(&tm); nvram_set("wl0_ifname", "ath0"); return; }
void Monitor::CalculateErrorFrequency(bool ise) { if(m_ErrorFreq>0) { if(ise) { CTimeSpan stime(0,0,m_Frequency,0); m_NextRunTime-=stime; CTimeSpan eftime(0,0,m_ErrorFreq,0); m_NextRunTime+=eftime; }else { CTimeSpan eftime(0,0,m_ErrorFreq,0); m_NextRunTime-=eftime; CTimeSpan stime(0,0,m_Frequency,0); m_NextRunTime+=stime; } } }
void set_time(GtkWidget *widget,gpointer data) { struct tm ti; time_t t; int i,tmp[6]; TIME *day=(TIME *)data; for(i=0; i<6; i++) tmp[i]=change_data(gtk_entry_get_text(GTK_ENTRY(day->data[i]))); if(tmp[0]<=1900) { error_message(widget,"输入的年份有误,请重新输入!"); return; } if(tmp[1]<1 || tmp[1]>12) { error_message(widget,"输入的月份有误,请重新输入!"); return; } if(tmp[2]<=0 || tmp[2]>31) { error_message(widget,"输入的日期有误,请重新输入!"); return; } if(tmp[3]<=0 || tmp[3]>24) { error_message(widget,"输入的小时有误,请重新输入!"); return; } if(tmp[4]<0 || tmp[4]>59) { error_message(widget,"输入的分钟数有误,请重新输入!"); return; } if(tmp[5]<0 || tmp[5]>59) { error_message(widget,"输入的秒数有误,请重新输入!"); return; } tmp[0]-=1900; ti.tm_year=tmp[0]; ti.tm_mon=tmp[1]; ti.tm_mday=tmp[2]; ti.tm_hour=tmp[3]; ti.tm_min=tmp[4]; ti.tm_sec=tmp[5]; t=mktime(&ti); stime(&t); error_message(widget,"设置成功!"); }
gint32 Mono_Posix_Syscall_stime (mph_time_t *t) { time_t _t; if (t == NULL) { errno = EFAULT; return -1; } mph_return_if_time_t_overflow (*t); _t = (time_t) *t; return stime (&_t); }
/* * Set the system time */ int set_time(time_t * new_time) { #if 0 if (stime(new_time)) { #endif perror("Unable to set time"); return -1; #if 0 } return 0; #endif }
int main(int ac, char **av) { int lc; /* loop counter */ char *msg; /* message returned from parse_opts */ /* Parse standard options given to run the test. */ msg = parse_opts(ac, av, (option_t *) NULL, NULL); if (msg != (char *)NULL) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); tst_exit(); } /* Perform global setup for test */ setup(); /* set the expected errnos... */ TEST_EXP_ENOS(exp_enos); /* Check looping state if -i option given */ for (lc = 0; TEST_LOOPING(lc); lc++) { /* Reset Tst_count in case we are looping. */ Tst_count = 0; /* * Invoke stime(2) to set the system's time * to the specified new_time as non-root user. */ TEST(stime(&new_time)); /* check return code of stime(2) */ if (TEST_RETURN == -1) { TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == EPERM) { tst_resm(TPASS, "stime(2) fails, Caller not " "root, errno:%d", TEST_ERRNO); } else { tst_resm(TFAIL, "stime(2) fails, Caller not " "root, errno:%d, expected errno:%d", TEST_ERRNO, EPERM); } } else { tst_resm(TFAIL, "stime(2) returned %ld, expected -1, " "errno:%d", TEST_RETURN, EPERM); } Tst_count++; /* incr TEST_LOOP counter */ } /* End for TEST_LOOPING */ /* Call cleanup() to undo setup done for the test. */ cleanup(); /*NOTREACHED*/ return 0; } /* End main */
string GetNowTime() { struct tm now; struct _timeb tb; _ftime_s(&tb); localtime_s(&now, &tb.time); char pAddrB[30]; sprintf_s(pAddrB, 30, "%04d-%02d-%02d %02d:%02d:%02d.%03d", now.tm_year + 1900, now.tm_mon + 1, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec, tb.millitm); string stime(pAddrB); return stime; }
FskErr KplTimeStime(SInt32 secs) { #ifdef ANDROID_PLATFORM FskErr err = kFskErrUnimplemented; return err; #else int result; FskErr err = kFskErrNone; time_t tsecs = secs; #if USE_POSIX_CLOCK result = stime(&tsecs); if (0 != result) err = kFskErrUnknown; #else struct timeval tv; FskTimeRecord b, a; gettimeofday(&tv, NULL); b.seconds = tv.tv_sec; b.useconds= tv.tv_usec; result = stime(&tsecs); gettimeofday(&tv, NULL); a.seconds = tv.tv_sec; a.useconds= tv.tv_usec; FskTimeSub(&b, &a); if (0 != result) err = kFskErrUnknown; else gDeltaTime.seconds += a.seconds; // stime only adjusts seconds #endif return err; #endif }
/** * Listener fot the nmea_parse function. Parses time from GPRMC sentence and quits the main loop. * * @param argc NMEA sentence arguments count * @param argv NMEA sentence arguments */ void message_complete(int argc, char argv[][32]) { if (argc == 14 && strcmp(argv[0], "GPRMC") == 0) { int hours, minutes, seconds; int day, month, year; /* Parse UTC time */ sscanf(argv[1], "%02d%02d%02d", &hours, &minutes, &seconds); sscanf(argv[9], "%02d%02d%02d", &day, &month, &year); year += 2000; if (day > 0 && day <= 31 && month > 0 && month <= 12 && year >= 2000) { if (hours >= 0 && hours < 24 && minutes >= 0 && minutes <= 60 && seconds >= 0 && seconds <= 60) { time_t curr_time; struct tm *timeinfo; /* Get current time, print it and modify */ time(&curr_time); timeinfo = localtime(&curr_time); printf("Local datetime was: %04d-%02d-%02d %02d:%02d:%02d (%s)\n", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday + 1, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, timeinfo->tm_zone); printf("GPS datetime is: %04d-%02d-%02d %02d:%02d:%02d (UTC)\n", year, month, day, hours, minutes, seconds); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day - 1; timeinfo->tm_hour = hours; timeinfo->tm_min = minutes; timeinfo->tm_sec = seconds; /* Calculate number of seconds since some old date, probably 1970s */ time_t gps_time = mktime(timeinfo); /* Add number of seconds from UTC (timezone is probably different from UTC) */ gps_time += timeinfo->tm_gmtoff; /* Set system time, may need root privilegies */ if (stime(&gps_time) == 0) { printf("Succesfully updated local time.\n"); } else { fprintf(stderr, "Local time can't be updated. Do you have root privilegies?\n"); } read_gps = 0; } } } }
bool TDateTime::SetCurrentDateTime(TDateTime &rhs) { #ifndef WIN32 unsigned int year=0, month=0, day=0, hour=0, min=0, sec=0; rhs.DecodeDate( year, month, day ); rhs.DecodeTime( hour, min, sec ); //更新操作系统时间 struct tm tmSys; time_t tSys; tmSys.tm_year = year - 1900; tmSys.tm_mon = month - 1; tmSys.tm_mday = day; tmSys.tm_sec = sec; tmSys.tm_min = min; tmSys.tm_hour = hour; tmSys.tm_isdst = -1; if ( ( tSys = mktime( &tmSys ) ) == -1 ) { DBG_PRN("info", ("mktime error!!")); return false; } if ( stime( &tSys ) == -1) { DBG_PRN("info", ("stime error!!")); return false; } //更RTC时间 // unsigned char tmp[3]; // int datetime; // datetime = rhs.FormatInt(YYYYMMDD); // int2bin(&tmp[0], (datetime / 10000) % 100, 1); // int2bin(&tmp[1], (datetime / 100) % 100, 1); // int2bin(&tmp[2], datetime % 100, 1); // SetRTCData(tmp); // // datetime = rhs.FormatInt(HHMMSS); // int2bin(&tmp[0], (datetime / 10000) % 100, 1); // int2bin(&tmp[1], (datetime / 100) % 100, 1); // int2bin(&tmp[2], datetime % 100, 1); // SetRTCTime(tmp); #endif return true; }