Ejemplo n.º 1
2
/*===========================================================================*
 *				do_setalarm				     *
 *===========================================================================*/
PUBLIC int do_setalarm(struct proc * caller, message * m_ptr)
{
/* A process requests a synchronous alarm, or wants to cancel its alarm. */
  long exp_time;		/* expiration time for this alarm */
  int use_abs_time;		/* use absolute or relative time */
  timer_t *tp;			/* the process' timer structure */
  clock_t uptime;		/* placeholder for current uptime */

  /* Extract shared parameters from the request message. */
  exp_time = m_ptr->ALRM_EXP_TIME;	/* alarm's expiration time */
  use_abs_time = m_ptr->ALRM_ABS_TIME;	/* flag for absolute time */
  if (! (priv(caller)->s_flags & SYS_PROC)) return(EPERM);

  /* Get the timer structure and set the parameters for this alarm. */
  tp = &(priv(caller)->s_alarm_timer);
  tmr_arg(tp)->ta_int = caller->p_endpoint;
  tp->tmr_func = cause_alarm; 

  /* Return the ticks left on the previous alarm. */
  uptime = get_uptime(); 
  if ((tp->tmr_exp_time != TMR_NEVER) && (uptime < tp->tmr_exp_time) ) {
      m_ptr->ALRM_TIME_LEFT = (tp->tmr_exp_time - uptime);
  } else {
      m_ptr->ALRM_TIME_LEFT = 0;
  }

  /* Finally, (re)set the timer depending on the expiration time. */
  if (exp_time == 0) {
      reset_timer(tp);
  } else {
      tp->tmr_exp_time = (use_abs_time) ? exp_time : exp_time + get_uptime();
      set_timer(tp, tp->tmr_exp_time, tp->tmr_func);
  }
  return(OK);
}
Ejemplo n.º 2
0
int my_clock_gettime(clockid_t clk_id, struct timespec *tp)
{	
	static int flag = 0;
	
	if(NULL == tp) {
		fprintf(std_err, "invalid argument.");
		return -1;
	}
	
#ifdef CONFIG_LOW_VERSION_LIBC
	tp->tv_sec = get_uptime();
	tp->tv_nsec = 0;
#else
	int ret = 0;
	int retry_count = 0;
	if (!flag) {
		while(((ret = clock_gettime(clk_id, tp)) < 0 ) && (retry_count ++ < 3)) {
			mysleep(0, 100);
		}

		if(ret < 0) {
			flag = 1;
			fprintf(std_err, "clock_gettime error[%s]", strerror(errno));
		}
	}
	
	if(flag) {
		tp->tv_sec = get_uptime();
		tp->tv_nsec = 0;
		flag = 1;
	}
#endif

	return 0;
}
Ejemplo n.º 3
0
void BusyBlinker::run(void)
{
	schedule(1); // Wait 1 ms.

	if(get_uptime() > counter) // If the LED needs to be toggled.
	{
		 // Set the counter to the next time the LED needs to be toggled.
		counter = get_uptime() + _interval;

		PINB = _pin; // Switch the LED's state.
	}
}
Ejemplo n.º 4
0
void CheckSystem::check_uptime(const Plugin::QueryRequestMessage::Request &request, Plugin::QueryResponseMessage::Response *response) {
	typedef check_uptime_filter::filter filter_type;
	modern_filter::data_container data;
	modern_filter::cli_helper<filter_type> filter_helper(request, response, data);
	std::vector<std::string> times;

	filter_type filter;
	filter_helper.add_options("uptime < 2d", "uptime < 1d", "", filter.get_filter_syntax(), "ignored");
	filter_helper.add_syntax("${status}: ${list}", filter.get_format_syntax(), "uptime: ${uptime}h, boot: ${boot} (UTC)", "uptime", "", "");

	if (!filter_helper.parse_options())
		return;

	if (!filter_helper.build_filter(filter))
		return;

	double uptime_secs = 0, idle_secs = 0;
	get_uptime(uptime_secs, idle_secs);
	unsigned long long value = uptime_secs;

	boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time();
	boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));
	boost::posix_time::ptime boot = now - boost::posix_time::time_duration(0, 0, value);

	long long now_delta = (now-epoch).total_seconds();
	long long uptime = static_cast<long long>(value);
	boost::shared_ptr<check_uptime_filter::filter_obj> record(new check_uptime_filter::filter_obj(uptime, now_delta, boot));
	filter.match(record);

	filter_helper.post_process(filter);
}
Ejemplo n.º 5
0
/** Return true iff <b>router</b> should be assigned the "HSDir" flag.
 *
 * Right now this means it advertises support for it, it has a high uptime,
 * it's a directory cache, it has the Stable and Fast flags, and it's currently
 * considered Running.
 *
 * This function needs to be called after router-\>is_running has
 * been set.
 */
static int
dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
                                const node_t *node, time_t now)
{

  long uptime;

  /* If we haven't been running for at least
   * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
   * have accurate data telling us a relay has been up for at least
   * that long. We also want to allow a bit of slack: Reachability
   * tests aren't instant. If we haven't been running long enough,
   * trust the relay. */

  if (get_uptime() >
      get_options()->MinUptimeHidServDirectoryV2 * 1.1)
    uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
                 real_uptime(router, now));
  else
    uptime = real_uptime(router, now);

  return (router->wants_to_be_hs_dir &&
          router->supports_tunnelled_dir_requests &&
          node->is_stable && node->is_fast &&
          uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
          router_is_active(router, node, now));
}
Ejemplo n.º 6
0
/*
 * plc_LoopInit()
 *
 * Description: T
 *  Gets the Uptime which will be used as NextTime the first time
 *  plc_LoopWait is called. 
 *
 */ 
pwr_tStatus plc_LoopInit (pwr_tVaxTime *NextTime)
{
    pwr_tStatus sts;

    ker$get_uptime(&sts, NextTime);
    return sts;
}
Ejemplo n.º 7
0
int get_uptime_string(char *newuptime, int *hours)
{
	long long tm;
	int seconds, minutes;
	int len;

	tm = get_uptime();
	if (tm == -1)
		return -1;

	/* seconds */
	*hours = (int)(tm / 1000000000LL);
	seconds = *hours % 60;

	/* minutes */
	*hours /= 60;
	minutes = *hours % 60;

	/* hours */
	*hours /= 60;

	len = snprintf(newuptime, UPTIME_SIZE, "%04d:%02d:%02d", *hours,
		       minutes, seconds);
	if (s_not_expect(len, UPTIME_SIZE))
		return -1;
	return 0;
}
Ejemplo n.º 8
0
/*
 * plc_LoopWait()
 *
 * Description:
 *  Returns FALSE if a slip is detected.
 */ 
pwr_tBoolean plc_LoopWait (
    int		*WaitResult,     /* Set to 1 when Event */
    pwr_tVaxTime	*DeltaTime,
    pwr_tVaxTime	*NextTime,
    unsigned long Event
)
{
    pwr_tStatus sts;
    pwr_tVaxTime NextLoop, UpTime, DiffTime;
    pwr_tBoolean Result;

    sts = lib$add_times(NextTime, DeltaTime, &NextLoop);
    *NextTime = NextLoop;
    ker$get_uptime(&sts, &UpTime);
    
    sts = lib$sub_times(NextTime, &UpTime, &DiffTime);
    if (sts == LIB$_NEGTIM) 
	Result = FALSE; /* Slip */
    else  if (NextTime->high == UpTime.high && NextTime->low == UpTime.low)
	Result = TRUE; /* Equal Times */
    else {
	if (Event)
	    ker$wait_any(&sts, WaitResult, &DiffTime, Event);
	else
	    ker$wait_any(&sts, WaitResult, &DiffTime);
	Result = TRUE;
    }	

    return Result;
}
Ejemplo n.º 9
0
static void start_stop_uptime(PERF_RTdata_uptime *dUptime, int start)
{
    double uptime, idletime;

    if (dUptime && dUptime->measuring != start)
    {
        /* add uptime since last time */
        get_uptime(&uptime, &idletime);

        /* if successful */
        if (dUptime->success && uptime && idletime)
        {
            dUptime->start_idletime = idletime - dUptime->start_idletime;
            dUptime->start_uptime = uptime - dUptime->start_uptime;
            dUptime->last_idletime = idletime - dUptime->last_idletime;
            dUptime->last_uptime = uptime - dUptime->last_uptime;
        }
        else
        {
            dUptime->start_idletime = dUptime->start_uptime = dUptime->success = 0;
            dUptime->last_idletime = dUptime->last_uptime = 0;
        }

        dUptime->measuring = start;
    }
}
Ejemplo n.º 10
0
void klog_write(int level, const char *fmt, ...)
{
    char buf[LOG_BUF_MAX];
    char *buf_ptr = buf;
    va_list ap;

    if ((level != KLOG_PROFLIE_LEVEL) && (level > klog_level)) return;
    if (klog_fd < 0) return;

    buf[0] = '\0';

#ifdef INIT_PROFILING
    static int last_uptime=0;
    int uptime = get_uptime();
    int dtime = uptime - last_uptime;
    sprintf(buf, "<%d>[%04d] [%04d] init: ", level, dtime, uptime);
    last_uptime = uptime;
#endif /* INIT_PROFILING */

    buf_ptr += strlen(buf);

    va_start(ap, fmt);
    vsnprintf(buf_ptr, LOG_BUF_MAX - strlen(buf), fmt, ap);
    buf[LOG_BUF_MAX - 1] = 0;
    va_end(ap);
    write(klog_fd, buf, strlen(buf));
}
Ejemplo n.º 11
0
static uint32_t loras_get_uptime_ms()
{
    SYSTIME uptime;
    uint32_t ms_passed;
    get_uptime(&uptime);
    ms_passed = (uptime.sec * 1000) + (uptime.usec / 1000);
    return ms_passed;
}
Ejemplo n.º 12
0
/* Function that checks if sleep time is over and assigne new sleep time. */
static int check_time(systime_t *sleep, const uint32_t freq) {
  timeval_t now = get_uptime();
  timeval_t diff = timeval_sub(&now, &start);
  if (tv2st(diff) < (*sleep))
    return 1;
  (*sleep) += (rand() & freq);
  return 0;
}
Ejemplo n.º 13
0
int main(int argc, char* argv[])
{

	print_title("BBN APS2 Enumerate Utility");

	set_logging_level(logDEBUG1);

	//First get the number of devices we can see
	unsigned numDevices = 0;
	get_numDevices(&numDevices);
	cout << concol::CYAN << numDevices << " APS device" << (numDevices > 1 ? "s": "")	<< " found" << concol::RESET << endl;
	cout << endl;

	//If we don't see anything bail
	if (numDevices < 1) return 0;

	//Get IP strings and firmware versions
	const char ** serialBuffer = new const char*[numDevices];
	get_device_IPs(serialBuffer);

	for (unsigned ct=0; ct < numDevices; ct++) {
		APS2_STATUS status;
		status = connect_APS(serialBuffer[ct]);
		if (status != APS2_OK) {
			cout << concol::RED << "Failed to connect to " << serialBuffer[ct] << concol::RESET << endl;
			continue;
		}

		char version_string[64];
		get_firmware_version(serialBuffer[ct], nullptr, nullptr, nullptr, version_string);
		double uptime{0};
		get_uptime(serialBuffer[ct], &uptime);
		std::chrono::duration<float> uptime_seconds(uptime);
		auto uptime_days = std::chrono::duration_cast<std::chrono::duration<int, std::ratio<24*3600>>>(uptime_seconds);

		std::ostringstream uptime_pretty;
		if (uptime_days.count()) {
			uptime_pretty << uptime_days.count() << " day" << (uptime_days.count() > 1 ? "s " : " ");
		}
		uptime_seconds -= uptime_days;
		auto uptime_hours = std::chrono::duration_cast<std::chrono::hours>(uptime_seconds);
		uptime_pretty << std::setfill('0') << std::setw(2) << uptime_hours.count() << ":";
		uptime_seconds -= uptime_hours;
		auto uptime_minutes = std::chrono::duration_cast<std::chrono::minutes>(uptime_seconds);
		uptime_pretty << std::setfill('0') << std::setw(2) << uptime_minutes.count() << ":";
		uptime_seconds -= uptime_minutes;
		uptime_pretty << std::fixed << std::setprecision(3) << uptime_seconds.count();

		cout << concol::CYAN << "Device " << ct << " at IPv4 address " << serialBuffer[ct] <<
		" running firmware version " << version_string <<
		" has been up " << uptime_pretty.str() << concol::RESET << endl;
		disconnect_APS(serialBuffer[ct]);
	}
	cout << endl;

	return 0;
}
Ejemplo n.º 14
0
/*
 * Update the applet
 */
int applet_check_uptime(UptimeApplet *applet) {
	get_uptime(applet);
	char uptime[128], tooltip[1024]; 

	format_uptime(applet, &uptime[0], &tooltip[0]);
	gtk_label_set_markup(GTK_LABEL(applet->label_bottom), &uptime[0]);
	gtk_widget_set_tooltip_text (GTK_WIDGET (applet->applet), &tooltip[0]);
	
	return TRUE;
}
Ejemplo n.º 15
0
static void *
download_thread(void *ptr)
{
	dl_thread_arg_t *in;
	struct stat file_stat;
	char file[16];
	double time_diff, time_thread;

	if (get_uptime(&time_thread)) {
		fprintf(stderr, "Error on getting /proc/uptime\n");
		return NULL;
	}
	time_diff = (time_thread - time_dl_start);
	if (time_diff > 10) {
		return NULL;
	}

	in = (dl_thread_arg_t *)ptr;

	strcpy(file, "/tmp/random");
	strcat(file, in->file_count);
	eval("curl", "-L", "-s", "-o", file, in->url);

	if (stat(file, &file_stat)) {
		fprintf(stderr, "stat file %s error\n", file);
		return NULL;
	}

	pthread_mutex_lock(&finished_mutex);
	finished += (double)file_stat.st_size;
	pthread_mutex_unlock(&finished_mutex);

	if (get_uptime(&time_thread)) {
		fprintf(stderr, "Error on getting /proc/uptime\n");
		return NULL;
	}
	time_diff = (time_thread - time_dl_start);
	printf("download = %.2f\n", ((finished / 1024 / 1024 / time_diff) * 8));

	eval("rm", file);

	return NULL;
}
Ejemplo n.º 16
0
int
procwalk()
{
    static int pwalk_per = 0;
    uint system_load = get_system_load(sampling);
    if (tillidle) {
        static uint idle_for_ms = 0;
        idle_for_ms = (system_load < idlecpu) ? idle_for_ms + millis : 0;
        idle = (idle_for_ms >= flag_after_ms);
    }

    count = 0;
    if (showmem) {
        SYSTEM_PERFORMANCE_INFORMATION sperf_info;
        if (get_system_performance_info(&sperf_info)) {
            fprintf (fp, "System committed memory (KB): %d / %d peak %d\n",
                     /* in pages so x4==KB */
                     4*sperf_info.TotalCommittedPages,
                     4*sperf_info.TotalCommitLimit,
                     4*sperf_info.PeakCommitment);
            /* FIXME: add physical memory, kernel memory, etc. */
        }
        fprintf (fp, "System load: %d%%\t\tUptime: %lu ms\n",
                 system_load, get_uptime());

        /* %user reaches 100% so we give it the extra column over %cpu */
        fprintf (fp, "%-23s %5s %7s %3s %4s %5s %3s %7s %7s %8s %7s %7s %7s %7s %5s %5s %5s %5s %5s",
                 "Name-Qualification", "PID", "DR  Bld", "CPU", "User", "Hndl", "Thr",
                 "PVSz", "VSz", "PPriv", "Priv",
                 "PWSS", "WSS", "Fault", "PPage", "Page", "PNonP", "NonP", "PPID");
        if (showtime)
            fprintf (fp, " %15s %15s %15s", "User Time(ms)", "Kernel Time(ms)",
                                            "Create Time(ms)");
        fprintf (fp, "\n");

    }
    if (pwalk_per == 0 || pwalk_per % showmemfreq == 0) {
        process_walk (&pw_callback, NULL);
        if (!count)
            fprintf (fp, "No such process found.\n");
        else {
            if (showmem && showtime) {
                fprintf (fp, "Total scheduled user/kernel time: %I64d/%I64d ms\n",
                         total_user/10000, total_kernel/10000);
            }
        }
    }
    pwalk_per++;

    total_user = 0;
    total_kernel = 0;

    return count;
}
Ejemplo n.º 17
0
static inline void stat()
{
    SYSTIME uptime;
    int i;
    unsigned int diff;

    get_uptime(&uptime);
    for (i = 0; i < TEST_ROUNDS; ++i)
        svc_test();
    diff = systime_elapsed_us(&uptime);
    printf("average kernel call time: %d.%dus\n", diff / TEST_ROUNDS, (diff / (TEST_ROUNDS / 10)) % 10);

    get_uptime(&uptime);
    for (i = 0; i < TEST_ROUNDS; ++i)
        process_switch_test();
    diff = systime_elapsed_us(&uptime);
    printf("average switch time: %d.%dus\n", diff / TEST_ROUNDS, (diff / (TEST_ROUNDS / 10)) % 10);

    printf("core clock: %d\n", power_get_core_clock());
    process_info();
}
Ejemplo n.º 18
0
static void *
upload_thread(void *ptr)
{
	ul_thread_arg_t *in;
	struct stat file_stat;
	double time_diff;
	double time_thread;

	if (get_uptime(&time_thread)) {
		fprintf(stderr, "Error on getting /proc/uptime\n");
		return NULL;
	}
	time_diff = time_thread - time_ul_start;
	if (time_diff > 10)
		return NULL;

	in = (ul_thread_arg_t *)ptr;

	eval("curl", "-L", "-s", "-0", "-d", in->ul_file, "-o", in->file_result, in->url);

	pthread_mutex_lock(&finished_mutex);
	if (stat(in->file_result, &file_stat)) {
		fprintf(stderr, "stat file %s error\n", in->file_result);
	} else {
		finished += (double)in->size;
	}
	pthread_mutex_unlock(&finished_mutex);

	if (get_uptime(&time_thread)) {
		fprintf(stderr, "Error on getting /proc/uptime\n");
		return NULL;
	}
	time_diff = (time_thread - time_ul_start);
	printf("upload = %.2f\n", ((finished / 1024 / 1024 / time_diff) * 8));

	eval("rm", in->file_result);

	return NULL;
}
Ejemplo n.º 19
0
/*===========================================================================*
 *				prepare_shutdown			     *
 *===========================================================================*/
void prepare_shutdown(const int how)
{
/* This function prepares to shutdown MINIX. */
  static timer_t shutdown_timer;

  /* Continue after 1 second, to give processes a chance to get scheduled to 
   * do shutdown work.  Set a watchog timer to call shutdown(). The timer 
   * argument passes the shutdown status. 
   */
  printf("MINIX will now be shut down ...\n");
  tmr_arg(&shutdown_timer)->ta_int = how;
  set_timer(&shutdown_timer, get_uptime() + system_hz, minix_shutdown);
}
Ejemplo n.º 20
0
static unsigned get_kernel_HZ(void)
{
	if (kernel_HZ)
		return kernel_HZ;

	/* Works for ELF only, Linux 2.4.0+ */
	kernel_HZ = find_elf_note(AT_CLKTCK);
	if (kernel_HZ == (unsigned)-1)
		kernel_HZ = get_HZ_by_waiting();

	G.seconds_since_boot = get_uptime();

	return kernel_HZ;
}
Ejemplo n.º 21
0
/* function: getting some systems informations
 * return: nothing, yust fill the struct statistics
 */
int get_sysinfos(void)
{
    // getting the hostname
    statistics.hostname=Strdup(read_hostname());
    // the revision of the image
    statistics.rev=Strdup(read_hardware(1));
    // the vendor + model
    statistics.vendor=Strdup(read_hardware(2));
    // the uptime
    statistics.uptime=Strdup(get_uptime());
    // the kernel version
    statistics.kernel=Strdup(kernelversion());
    // the CPU version
    statistics.cpu=Strdup(get_cpuinfo());
    return 0;
}
Ejemplo n.º 22
0
int main()
{
    char buf[BUF_SIZE];
    
    get_cpu_type(buf, sizeof(buf));
    printf("CPU Type: %s\n", buf);
    
    get_kernel_version(buf, sizeof(buf));
    printf("Kernel Version: %s\n", buf);
    
    get_uptime(buf, sizeof(buf));
    calc_time(buf, buf, sizeof(buf));
    printf("Time since bootup: %s\n", buf);

    return 0;
}
Ejemplo n.º 23
0
Message::Message():
	_parsing_body(false),
	_current_line(NULL),
	_type(UNKNOWN),
	_dispatching_type(UNDETERMINED),
#if MESSAGE_AGE
	_age(get_uptime()), //Set the uptime at which the message was created.
#endif
	body(NULL),
	to_url_cursor(0),
	from_url_cursor(0),
	to_url(NULL),
	from_url(NULL),
	content_type(NULL),
	fields(NULL)
{
}
Ejemplo n.º 24
0
static void*
handle_stats(enum mg_event event,
             struct mg_connection *conn,
             const struct mg_request_info *request_info) {
    print_HTTP_response(conn, 200, "OK");
    mg_printf(conn, "Answered %d queries\n", nreq);
    mg_printf(conn, "Uptime: %s\n", get_uptime().c_str());

    if (building) {
        mg_printf(conn, "Data Store is busy\n");
    }
    else {
        mg_printf(conn, "Data store size: %d entries\n", pm.repr.size());
    }
    mg_printf(conn, "Memory usage: %d MiB\n", get_memory_usage(getpid())/1024);

    return (void*)"";
}
Ejemplo n.º 25
0
static void handle_stats(client_t *client, parsed_url_t &url) {
    headers_t headers;
    headers["Cache-Control"] = "no-cache";

    std::string body;
    char buff[2048];
    char *b = buff;
    b += sprintf(b, "Answered %lu queries\n", nreq);
    b += sprintf(b, "Uptime: %s\n", get_uptime().c_str());

    if (building) {
        b += sprintf(b, "Data Store is busy\n");
    }
    else {
        b += sprintf(b, "Data store size: %d entries\n", pm.repr.size());
    }
    b += sprintf(b, "Memory usage: %d MiB\n", get_memory_usage(getpid())/1024);
    body = buff;
    write_response(client, 200, "OK", headers, body);
}
Ejemplo n.º 26
0
void show_uptime() {
    char result[128];
    strcpy(result, "");

    long uptime = get_uptime();

    long day = uptime / (24 * 60 * 60);
    long hour = (uptime / (60 * 60) - day * 24);
    long minute = ((uptime / 60) - day * 24 * 60 - hour * 60);
    long second = (uptime - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60);

    lcd_draw_string(9 * 2, 0, "Uptime");

    if (day > 0) {
        char tmp[10];
        sprintf(tmp, "%ldd", day);
        strcat(result, tmp);
    } 
    
    if (day > 0 || hour > 0) {
        char tmp[10];
        sprintf(tmp, "%ldh", hour);
        strcat(result, tmp);
    } 
    
    if (minute > 0) {
        char tmp[10];
        sprintf(tmp, "%ldm", minute);
        strcat(result, tmp);
    } 

    if (hour <= 0 && second > 0) {
        char tmp[3];
        sprintf(tmp, "%lds", second);
        strcat(result, tmp);
    }
    
    lcd_draw_string(9 * 2, 128 - 8 * strlen(result), result);
}
Ejemplo n.º 27
0
static int compute_key(char *key, size_t klen, const char *seed,
			const size_t slen)
{
	SHA256_CTX sha;
	char buf[VERSION_SIZE];
	int len;
	long long time_ns;
	char *tmp_key = key;
	unsigned char results[SHA256_DIGEST_LENGTH];
	size_t i;

	if (!key || !seed || !slen)
		return -1;
	if (klen > SHA256_DIGEST_LENGTH * 2 || !klen)
		return -1;

	SHA256_Init(&sha);
	time_ns = get_uptime();
	len = snprintf(buf, VERSION_SIZE, "%s%s%lld",
			gbuildversion, guuid, time_ns);
	if (s_not_expect(len , VERSION_SIZE))
		return -1;

	SHA256_Update(&sha, (unsigned char *)buf, strnlen(buf, VERSION_SIZE));
	SHA256_Update(&sha, (unsigned char *)seed, strnlen(seed, slen));

	SHA256_Final(results, &sha);

	for (i = 0; i < klen / 2; i++) {
		len = snprintf(tmp_key, 3, "%02x", results[i]);
		if (s_not_expect(len, 3))
			return -1;
		tmp_key += 2;
	}
	*tmp_key = 0;

	return 0;
}
Ejemplo n.º 28
0
static pwr_tTime *
nowTime (
  pwr_tTime		*tp
)
{
#if defined OS_VMS
  /* This code is valid up to 497 days after boot.  */

  void			*argv[3];
  pwr_tStatus		sts;

  argv[0] = (void *) 2;
  argv[1] = &tp->tv_sec;
  argv[2] = &tp->tv_nsec;

  sts = sys$cmexec(&vmsUpTime, argv);

  tp->tv_nsec %= 100;
  tp->tv_nsec *= 10000000;

#elif defined OS_ELN

  pwr_tStatus		sts;
  int			tmp[2];
  int			div = -10000000;

  ker$get_uptime(&sts, &tmp);

  sts = lib$ediv(&div, &tmp, &tp->tv_sec, &tp->tv_nsec);

  tp->tv_nsec *= -100;

#elif defined OS_LYNX
  clock_gettime(CLOCK_REALTIME, tp);
#endif
 
  return tp;
}
Ejemplo n.º 29
0
static int stress_test(void) {

  threads[0] = thread_create("Thread clear1", thread_test, &klog_clear);
  threads[1] = thread_create("Thread add logs1", thread_test, &logs);
  threads[2] = thread_create("Thread dump1", thread_test, &klog_dump);
  threads[3] = thread_create("Thread clear2", thread_test, &klog_clear);
  threads[4] = thread_create("Thread add logs2", thread_test, &logs);
  /* Note, if we use more then one dump some output could be lost and/or
   * misplaced */
  /* threads[5] = thread_create("Thread dump2", thread_test, &klog_dump); */

  int number_of_threads = 5;
  start = get_uptime();
  for (int i = 0; i < number_of_threads; i++)
    sched_add(threads[i]);

  for (int i = 0; i < number_of_threads; i++)
    thread_join(threads[i]);

  klog_clear();

  return 0;
}
Ejemplo n.º 30
0
int main (int argc, char *argv[])
{
	Arguments args;
	int i, use_taskstat;
	int in_initrd, clean_environment = 1;
	int stat_fd, disk_fd, uptime_fd, meminfo_fd,  pid, ret = 1;
	PidScanner *scanner = NULL;
	unsigned long reltime = 0;
	BufferFile *stat_file, *disk_file, *per_pid_file, *meminfo_file;
	PidEventClosure pid_ev_cl;
	int *fds[] = { &stat_fd, &disk_fd, &uptime_fd, &meminfo_fd, NULL };
	const char *fd_names[] = { "/stat", "/diskstats", "/uptime", "/meminfo", NULL };
	StackMap map = STACK_MAP_INIT; /* make me findable */

	arguments_set_defaults (&args);
	arguments_parse (&args, argc, argv);

	if (args.usleep_time > 0) {
		usleep (args.usleep_time);
		return 0;
	}

	if (enter_environment (args.console_debug))
		return 1;

	fprintf (stderr, "bootchart-collector started as pid %d with %d args: ",
		 (int) getpid(), argc - 1);
	for (i = 1; i < argc; i++)
		fprintf (stderr, "'%s' ", argv[i]);
	fprintf (stderr, "\n");

	if (args.dump_path) {
		Arguments remote_args;

		ret = buffers_extract_and_dump (args.dump_path, &remote_args);
		ret |= dump_header (args.dump_path);

		if (!remote_args.relative_time)
			ret |= dump_dmsg (args.dump_path);
		if (!ret)
			cleanup_dev ();
		goto exit;
	}

	if (!args.relative_time) { /* manually started */
		in_initrd = am_in_initrd ();
		if (in_initrd && sanity_check_initrd ())
			goto exit;
	}

	pid = bootchart_find_running_pid (NULL);
	if (args.probe_running) {
		clean_environment = pid < 0;
		ret = pid < 0;
		goto exit;
	} else {
		if (pid >= 0) {
			clean_environment = 0;
			fprintf (stderr, "bootchart collector already running as pid %d, exiting...\n", pid);
			goto exit;
		}
	}
      
	/* defaults */
	if (!args.hz)
		args.hz = 50;

	for (i = 0; fds [i]; i++) {
		char *path = malloc (strlen (PROC_PATH) + strlen (fd_names[i]) + 1);
		strcpy (path, PROC_PATH);
		strcat (path, fd_names[i]);

		*fds[i] = open (path, O_RDONLY);
		if (*fds[i] < 0) {
			fprintf (stderr, "error opening '%s': %s'\n",
				 path, strerror (errno));
			exit (1);
		}
	}

	stat_file = buffer_file_new (&map, "proc_stat.log");
	disk_file = buffer_file_new (&map, "proc_diskstats.log");
	if ( (use_taskstat = init_taskstat()) )
		per_pid_file = buffer_file_new (&map, "taskstats.log");
	else
		per_pid_file = buffer_file_new (&map, "proc_ps.log");
	meminfo_file = buffer_file_new (&map, "proc_meminfo.log");
	pid_ev_cl.cmdline_file = buffer_file_new (&map, "cmdline2.log");
	pid_ev_cl.paternity_file = buffer_file_new (&map, "paternity.log");

	if (!stat_file || !disk_file || !per_pid_file || !meminfo_file ||
	    !pid_ev_cl.cmdline_file || !pid_ev_cl.paternity_file) {
		fprintf (stderr, "Error allocating output buffers\n");
		return 1;
	}

	scanner = pid_scanner_new_netlink (pid_event_cb, &pid_ev_cl);
	if (!scanner)
		scanner = pid_scanner_new_proc (PROC_PATH, pid_event_cb, &pid_ev_cl);
	if (!scanner)
		return 1;

	if (args.relative_time) {
		reltime = get_uptime (uptime_fd);
		if (! reltime)
			exit (1);
	}

	while (1) {
		pid_t pid;
		char uptime[80];
		size_t uptimelen;
		unsigned long u;

		if (in_initrd) {
			if (have_dev_tmpfs ()) {
				if (chroot_into_dev ()) {
					fprintf (stderr, "failed to chroot into /dev - exiting so run_init can proceed\n");
					return 1;
				}
				in_initrd = 0;
			}
		}
      
		u = get_uptime (uptime_fd);
		if (!u)
			return 1;

		uptimelen = sprintf (uptime, "%lu\n", u - reltime);

		buffer_file_dump_frame_with_timestamp (stat_file, stat_fd, uptime, uptimelen);
		buffer_file_dump_frame_with_timestamp (disk_file, disk_fd, uptime, uptimelen);
		buffer_file_dump_frame_with_timestamp (meminfo_file, meminfo_fd, uptime, uptimelen);

		/* output data for each pid */
		buffer_file_append (per_pid_file, uptime, uptimelen);

		pid_scanner_restart (scanner);
		while ((pid = pid_scanner_next (scanner))) {

			if (use_taskstat)
				dump_taskstat (per_pid_file, scanner);
			else
				dump_proc_stat (per_pid_file, pid);
		}
		buffer_file_append (per_pid_file, "\n", 1);

		usleep (1000000 / args.hz);
	}

	/*
	 * In reality - we are always killed before we reach
	 * this point
	 */
	if (use_taskstat) {
		if (close (netlink_socket) < 0) {
			perror ("failed to close netlink socket");
			exit (1);
		}
	}

	for (i = 0; fds [i]; i++) {
		if (close (*fds[i]) < 0) {
			fprintf (stderr, "error closing file '%s': %s'\n",
				 fd_names[i], strerror (errno));
			return 1;
		}
	}

	ret = 0;

 exit:
	arguments_free (&args);

	if (scanner)
		ret |= pid_scanner_free (scanner);

	if (clean_environment)
		clean_enviroment();

	return ret;
}