Ejemplo n.º 1
0
/*
 * Read counts of page faults from a string.
 * choice: 1 - minor, 2 - major
 */
unsigned long get_page_fault_from_string(char * string, int choice) {
#ifndef __APPLE__
	struct proc_stats statsData; // Stat for storing information from the /proc/pid/stat file
	int self = getpid(); // Process ID

	// First write string to a file.
	FILE *fp = fopen("temp", "wb+"); // Use a temporary file.
	if (fp != NULL)
	{
		fputs(string, fp);
		if (fp) {
			fclose(fp);
		}
	} else {
		printf("Error opening a temp file.\n");
	}

	// Read data from the stats file
	read_stat("temp", self, &statsData);

	// Return the count of detected page faults.
	if (choice == 1) {
		return statsData.minflt;

	} else {
		return statsData.majflt;
	}

#else
	return -1;
#endif
}
Ejemplo n.º 2
0
static int do_sbufl_fill_from_file(struct sbuf *sb, FILE *fp, gzFile zp,
	int phase1, struct cntr *cntr)
{
	int ars;
	struct iobuf rbuf;
	//free_sbufl(sb);
	iobuf_init(&rbuf);
	if((ars=read_stat(NULL /* no async */,
		&rbuf, fp, zp, sb, cntr))) return ars;
	if((ars=read_fp(fp, zp, &rbuf))) return ars;
	iobuf_copy(&sb->path, &rbuf);
	if(sbuf_is_link(sb))
	{
		if((ars=read_fp(fp, zp, &rbuf))) return ars;
		iobuf_copy(&sb->link, &rbuf);
		if(!cmd_is_link(rbuf.cmd))
			return unexpected(&rbuf, __func__);
	}
	else if(!phase1 && sbuf_is_filedata(sb))
	{
		if((ars=read_fp(fp, zp, &rbuf))) return ars;
		iobuf_copy(&(sb->burp1->endfile), &rbuf);
		if(!cmd_is_endfile(rbuf.cmd))
			return unexpected(&rbuf, __func__);
	}
	return 0;
}
Ejemplo n.º 3
0
static int64_t
read_bd_stat(int device, int domid, const char *str)
{
    static const char *paths[] = {
        "/sys/bus/xen-backend/devices/vbd-%d-%d/statistics/%s",
        "/sys/bus/xen-backend/devices/tap-%d-%d/statistics/%s",
        "/sys/devices/xen-backend/vbd-%d-%d/statistics/%s",
        "/sys/devices/xen-backend/tap-%d-%d/statistics/%s"
    };

    int i;
    char *path;
    int64_t r;

    for (i = 0; i < ARRAY_CARDINALITY(paths); ++i) {
        if (virAsprintf(&path, paths[i], domid, device, str) < 0) {
            virReportOOMError();
            return -1;
        }

        r = read_stat(path);

        VIR_FREE(path);

        if (r >= 0) {
            return r;
        }
    }

    return -1;
}
Ejemplo n.º 4
0
static void poll()
{
	uint8_t stat;

	do
		stat = read_stat(sel_base_port);
	while ((stat & BSY) != 0); // TODO: Error detection
}
Ejemplo n.º 5
0
static void check_drive(uint16_t base, uint8_t master_or_slave)
{
	if (sel_base_port != 0) // Check if we've already found a drive
		return;

	outb(base + DRIVE_SELECT, master_or_slave); // select the drive

	// Zero out these 4 ports
	outb(base + SECTOR_COUNT, 0);
	outb(base + LBA_LOW,      0);
	outb(base + LBA_MID,      0);
	outb(base + LBA_HIGH,     0);

	outb(base + COM_STAT,  IDENTIFY); // Send IDENTIFY command
	uint8_t stat = read_stat(base);

	if (stat == 0) // The drive does not exist
		return;

	// It exists! Retrieve some status info

	while ((stat & BSY) != 0) // Poll status port until BSY clears
		stat = read_stat(base);

	// TODO: check for ATAPI at this point

	while ((stat & DRQ) == 0 && (stat & ERR) == 0)
		stat = read_stat(base);

	if ((stat & ERR) != 0) // Something's wrong. Maybe it's ATAPI or SATA
		return;

	// The drive is ready to send us 256 (16-bit) words of data
	uint16_t drive_data[256];
	for (size_t i = 0; i < 256; i++)
		drive_data[i] = inw(base + DATA);

	max_sector = drive_data[MAX_28LBA_SECTORS] |
		drive_data[MAX_28LBA_SECTORS + 1] << 16;

	// This drive seems to work, so let's select it
	sel_base_port       = base;
	sel_master_or_slave = master_or_slave;
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
    args list;
    int fd;
    pid_t pid;
    int size = 0;
    int i = 1;
    int nodes_num = 0;
    char sz[25];
    char pipe_path[30];

    if(process_c_args(argc, argv, &list))
    {
        return -1;
    }

    size = strtol(list.file_name, NULL, 10);
    snprintf(sz, 25, "%d", size);

    if(mkfifo ("/tmp/1_p",0666) == -1)
    {
        perror("Error creating named pipe");
    }


    pid = fork();
    if(pid == 0) //child
    {
        //SM node arguments: lower bound, upper bound, sorting attribute, file name, node number, current depth, max depth
        execl("smnode", "smnode", "0", sz, list.attrib, list.file_name, "1", "0", list.depth, (char *)0);
        fflush(stdout);
        perror("Can't execute smnode\n");
    } else if (pid < 0) //fork failed
    {
        perror("Fork error!\n");
    } else //parent
    {
        fd = open("/tmp/1_p", O_RDONLY);
        read_fifo(fd,size);
        close(fd);
    }

    printf("\n\n ======================= Sorting Statistics ======================= \n\n");
    read_stat();
    printf("\n\n ================================================================== \n\n");

    //remove the pipes when finished
    nodes_num = (int)(pow(2,atoi(list.depth)+1)) - 1;
    for(i = 1; i <= nodes_num; i++)
    {
        snprintf(pipe_path, 30, "/tmp/%d_p", i);
        unlink(pipe_path);
    }
    return 0;
}
Ejemplo n.º 7
0
/* ------------------------------------------------------------------
 * Opens and iterates through a given directory, operating on allowed
 * files found within it.  . and .. are skipped, as are files beginning
 * with . unless it's been enabled in the flags.  All other entries,
 * both files and directories, are thrown to process_entry to determine
 * whether they're a file/directory/link, and to read/explore them if
 * appropriate.  If threads are being used, they wait for their children
 * threads to terminate after they themselves are done with their work.
 *
 * flags:	The usual I/O option flags.
 * list_head:	A list of already visited directories.  Always will have
 *		the working directory low was called from as the tail,
 *		and will always have the current directory being explored
 *		as the head (so the src = list_head->next->path assignment
 *		is always safe).
 * fullpath:	The realpath of the current directory being explored.
 * dir_depth:	Passed to process_entry.
 * ------------------------------------------------------------------
 */
int explore_dir(params *P, visited_dir *list_head, char *nextpath, 
		int dir_depth)
{
	DIR *d;
	struct dirent *entry;
	struct dirent **done;
	int len;
	
	if ( (d = opendir(nextpath)) == 0)
	{
		return print_file_error(P, errno, nextpath);
	}
	
	if (((P->max_dir_depth) - dir_depth) > read_stat(P, t_ddepth))
		update_stat(P, t_ddepth, ((P->max_dir_depth) - dir_depth));
	
	len = offsetof(struct dirent, d_name) + 
		pathconf(nextpath, _PC_NAME_MAX) + 1;
	if ((entry = malloc(len)) == NULL || 
			(done = malloc(sizeof(struct dirent*))) == NULL)
	{
		fprintf(stderr, "Malloc failed in explore_dir.\n");
		return -1;
	}
	done = &entry;

	while ( (readdir_r(d, entry, done)) == 0 && (*done != NULL))
	{
		/* don't process '.' or '..' in a directory! */
		if ( (strcmp(entry->d_name, THIS_DIR) == 0) 
			|| (strcmp(entry->d_name, PARENT_DIR) == 0))
			continue;

		/* do all files but ones beginning with a dot,
		 * unless we've enabled it! */
		if (entry->d_name[0] == '.')
		{
			if (enabled(P, READ_DOT_FILES))
			{
				process_entry(P, list_head, entry->d_name,
					nextpath, dir_depth, 0);
			}
			else
				inc_stat(P, t_dotfiles, 1);
		}
		else
			process_entry(P, list_head, entry->d_name, nextpath,
				dir_depth, 0);
	}
	closedir(d);
	wait_for_children(list_head);
	free(nextpath);
	return 0;	
}
Ejemplo n.º 8
0
/*
 * Read information from the /proc/stat file.
 */
struct proc_stats get_page_fault_file() {
	struct proc_stats statsData; 	// Struct to hold data from the /proc/pid/stat file
	int self = getpid(); 			// Process ID

	char buf[256]; // Buffer for reading in content of the file

	// Read data from the stats file
	sprintf(buf, "/proc/%d/stat", self);
	read_stat(buf, self, &statsData);

	return statsData;
}
Ejemplo n.º 9
0
/* ------------------------------------------------------------------
 * Interface for threads to call explore_dir from, pretty much.
 * ------------------------------------------------------------------
 */
void* thread_dir_setup(void *info)
{
	dir_info *d = (dir_info*) info;
	params *P = d->parameters;
	inc_stat(P, t_threadsmade, 1);
	
	pthread_mutex_lock(&stats_mutex);
	(P->threads_left) -= 1;
	pthread_mutex_unlock(&stats_mutex);

	inc_stat(P, current_tcount,1);
	if (read_stat(P, current_tcount) > read_stat(P, t_threadssim))
		update_stat(P, t_threadssim, read_stat(P, current_tcount));
	explore_dir(P, d->list, d->path, d->dir_d);

	pthread_mutex_lock(&stats_mutex);
	(P->threads_left) += 1;
	pthread_mutex_unlock(&stats_mutex);
	inc_stat(P, current_tcount, -1);
	free_dir_info(info);
	return 0;
}	
Ejemplo n.º 10
0
int
main (int argc, char **argv)
{
	unsigned int length = 1;
	unsigned int current = 0;

	while (1) {
		if (read_stat (&current, &length) == 0)
			/* print message in form [P 0.xxxxx]\n */
			printf ("[P %f]\n", (double) current / (double) length);
		usleep (PRINTOUT_INTERVAL * 1000000);
	}
}
Ejemplo n.º 11
0
int statement()
{
	int es = 0;
	if (es == 0 && strcmp(token, "if") == 0) es = if_stat();//<IF语句>
	if (es == 0 && strcmp(token, "while") == 0) es = while_stat();//<while语句>
	if (es == 0 && strcmp(token, "for") == 0) es = for_stat();//<for语句>
	//可在此处添加do语句调用
	if (es == 0 && strcmp(token, "read") == 0) es = read_stat();//<read语句>
	if (es == 0 && strcmp(token, "write") == 0) es = write_stat();//<write语句>
	if (es == 0 && strcmp(token, "{") == 0) es = compound_stat();//<复合语句>
	if (es == 0 && (strcmp(token, "ID") == 0 || strcmp(token, "NUM") == 0 || strcmp(token, "(") == 0)) es = expression_stat();//<表达式语句>
	return(es);
}
Ejemplo n.º 12
0
void stat(){
	if (lookahead == INTEGER || lookahead == STRING || lookahead == BOOLEAN || lookahead == TABLE)
		def_stat();
	else if (lookahead == ID)
		assign_stat();
	else if (lookahead == IF)
		if_stat();
	else if (lookahead == WHILE)
		while_stat();
	else if (lookahead == READ)
		read_stat();
	else //(lookahead == WRITE)
		write_stat();
}
Ejemplo n.º 13
0
/* Library finalizer function */
static void __attribute__((destructor)) interpose_fini(void) {

    /* Look for descriptors not explicitly closed */
    for(int i=0; i<max_descriptors; i++) {
        trace_close(i);
    }

    read_exe();
    read_status();
    read_stat();
    read_io();

    tprintf("stop: %lf\n", get_time());

    /* Close trace file */
    tclose();
}
Ejemplo n.º 14
0
Archivo: client.c Proyecto: hpc/Spindle
int get_stat_result(int fd, const char *path, int is_lstat, int *exists, struct stat *buf)
{
   int result;
   char buffer[MAX_PATH_LEN+1];
   char cache_name[MAX_PATH_LEN+3];
   char *newpath;
   int use_cache = (opts & OPT_SHMCACHE) && (shm_cachesize > 0);
   int found_file = 0;

   if (use_cache) {
      debug_printf2("Looking up %sstat for %s in shared cache\n", is_lstat ? "l" : "", path);
      get_cache_name(path, is_lstat ? "**" : "*", cache_name);
      cache_name[sizeof(cache_name)-1] = '\0';
      found_file = fetch_from_cache(cache_name, &newpath);
   }

   if (!found_file) {
      result = send_stat_request(fd, (char *) path, is_lstat, buffer);
      if (result == -1) {
         *exists = 0;
         return -1;
      }
      newpath = buffer[0] != '\0' ? buffer : NULL;

      if (use_cache) 
         shmcache_update(cache_name, newpath);
   }
   
   if (newpath == NULL) {
      *exists = 0;
      return 0;
   }
   *exists = 1;

   test_log(newpath);
   result = read_stat(newpath, buf);
   if (result == -1) {
      err_printf("Failed to read stat info for %s from %s\n", path, newpath);
      *exists = 0;
      return -1;
   }
   return 0;
}
Ejemplo n.º 15
0
/*Genera il codice per il nodo stat_list e crea lo scope del programma*/
Code stat_list(Pnode stat_list_node){
	//Definisco la variabile che contiene il codice da ritornare
	Code stat_list_code;
	stat_list_code.head = NULL;
	stat_list_code.tail = NULL;
	stat_list_code.size = 0;

	//Creo l'ambiente del programma
	push_environment();
	
	//Punto al primo stat
	Pnode stat_node = stat_list_node->child;
	//Ciclo lungo tutti gli stat_node
	while (stat_node!=NULL){
		//Creo il codice dello stat_node
		Code stat_code;
		switch (stat_node->type){
			case(N_DEF_STAT): 	stat_code = def_stat(stat_node);break;
			case(N_ASSIGN_STAT): 	stat_code = assign_stat(stat_node);break;
			case(N_IF_STAT): 	stat_code = if_stat(stat_node);break;
			case(N_WHILE_STAT): 	stat_code = while_stat(stat_node);break;
			case(N_READ_STAT): 	stat_code = read_stat(stat_node);break;
			case(N_WRITE_STAT): 	stat_code = write_stat(stat_node);break;
		}
		
		//Appendo il codice a stat_list_code
		stat_list_code = appcode(stat_list_code,stat_code);

		//Punto al fratello successivo
		stat_node = stat_node->brother;
	}
	
	//Appendo il codice per fare il pop dell'environment a stat_list_code
	if(numobj_in_current_env()!=0)
		stat_list_code = appcode(stat_list_code,makecode1(T_POP,numobj_in_current_env()));

	//elimino l'ambiente creato (elimina già le variabili dall'ambiente)
	pop_environment();

	return stat_list_code;
}
Ejemplo n.º 16
0
static int do_sbufl_fill_from_net(struct sbuf *sb, struct asfd *asfd,
	struct cntr *cntr)
{
	int ars;
	static struct iobuf *rbuf=NULL;
	rbuf=asfd->rbuf;
	iobuf_free_content(rbuf);
	if((ars=read_stat(asfd, rbuf, NULL, NULL, sb, cntr))
	  || (ars=asfd->read(asfd))) return ars;
	iobuf_copy(&sb->path, rbuf);
	rbuf->buf=NULL;
	if(sbuf_is_link(sb))
	{
		if((ars=asfd->read(asfd))) return ars;
		iobuf_copy(&sb->link, rbuf);
		rbuf->buf=NULL;
		if(!cmd_is_link(rbuf->cmd))
			return unexpected(rbuf, __func__);
	}
	return 0;
}
Ejemplo n.º 17
0
Code stat(Pnode p)
{
    switch (p->type)
    {
        case N_DEF_STAT:
            return def_stat(p);
        case N_ASSIGN_STAT:
            return assign_stat(p);
        case N_IF_STAT:
            return if_stat(p);
        case N_WHILE_STAT:
            return while_stat(p);
        case N_READ_STAT:
            return read_stat(p);
        case N_WRITE_STAT:
            return write_stat(p);
        default:
            noderror(p);
    }
    return endcode();
}
Ejemplo n.º 18
0
Archivo: downboy2.c Proyecto: anl/IT
main(int argc,char *argv[])
{
   int k=-1; /* kill threshold in CPU seconds */

   override_type *override_list;
   struct dirent *dir_entry_p;
   DIR *dir_p;
   int uid;

   int opt;

   while ((opt=getopt(argc,argv,"k:h"))!=-1)
      switch (opt)
         {
         case 'k': /* kill threshold in CPU seconds */
            if ((k=atoi(optarg))>0)
               break;

         case '?': /* miscellaneous error condition */
         case 'h': /* help! */
            fprintf(stderr,"downboy2 [-k kill_threshold_in_CPU_seconds]\n");
            exit(-1);
         }

   if ((dir_p=opendir(PROC_ROOT))==NULL)
      fprintf(stderr,"Error: failed to open '%s'!\n",PROC_ROOT);
   else
      {
      override_list=load_override(OVERRIDE_FILE);

      while ((dir_entry_p=readdir(dir_p))!=NULL)
         if (COUNT_DIGITS(dir_entry_p->d_name)==strlen(dir_entry_p->d_name)
            && (uid=get_owner(dir_entry_p->d_name))!=0) /* if not root */
            read_stat(dir_entry_p->d_name,find_override(override_list,uid),
               k,uid);

      closedir(dir_p);
      }
}
Ejemplo n.º 19
0
int main (int argc, char** argv) {
  int stat_fd;
  int led_fd;
  int led_trigger_fd;

  int idle;
  int blink_delay = base_delay;
  int tblink = blink_delay; /* time until next blink */
  int tupdate = update_delay; /* time until next update */

  /* Disable led triggers to get us free access to the led */
  led_trigger_fd = open(led_trigger_path, O_WRONLY);
  assert(led_trigger_fd >= 0);
  write(led_trigger_fd, "none\n", 5);
  close(led_trigger_fd);

  stat_fd = open(procstat, O_RDONLY);
  assert(stat_fd >= 0);

  led_fd = open(led_control_path, O_WRONLY|O_TRUNC);
  assert(led_fd >= 0);

  while(1) {
    idle = read_stat(stat_fd);
    tblink -= blink_delay;
    blink_delay = (min_delay * 100 + (base_delay - min_delay) * idle) / 100;
    tblink += blink_delay;
    tblink = tblink < 0 ? 0 : tblink;
    while (tblink < tupdate) {
      usleep(tblink);
      tupdate -= tblink;
      tblink = blink_delay;
      blink(led_fd);
    }
    usleep (tupdate);
    tblink -= tupdate;
    tupdate = update_delay;
  }
}
Ejemplo n.º 20
0
int
main( int argc, char *argv[] )
{
     DirectResult         ret;
     FusionWorld         *world;
     FusionCall           call = {0};
     FusionSHMPoolShared *pool;
     void                *buffer;
     int           i, max_busy = 0, active = 1;
     long long     t1 = 0, t2;
     long long     start       = 0;
     long long     bytes       = 0;
     long long     last_bytes  = 0;
     unsigned long blocks      = 0;
     unsigned long last_blocks = 0;
     unsigned long last_busy   = 0;
     u32           checksum    = 0;
     bool          produce     = true;
     int           delay       = 66000;

     if (parse_cmdline( argc, argv ))
          return -1;

     if (bit_rate) {
          int blocks_per_sec = (bit_rate * 1024 / 8) / block_size;

          if (blocks_per_sec < 100)
               delay = 900000 / blocks_per_sec - 2000;
          else
               delay = 300000 * 100 / blocks_per_sec;

          num_blocks = bit_rate * 1024 / 8 / block_size * delay / 900000;

          if (num_blocks > MAX_NUM_BLOCKS)
               num_blocks = MAX_NUM_BLOCKS;

          if (!num_blocks) {
               num_blocks = 1;
               delay = 970 * block_size / (bit_rate * 1024 / 8) * 1000 - 2000;
          }
     }

     sync();

     if (run_busy) {
          pthread_create( &busy_thread, NULL, busy_loop, NULL );

          printf( "Calibrating...\n" );
     
          pthread_mutex_lock( &busy_lock );
     
          for (i=0; i<7; i++) {
               int busy_rate;
     
               busy_count = 0;
     
               t1 = get_millis();
               pthread_mutex_unlock( &busy_lock );
     
               usleep( 300000 );
     
               pthread_mutex_lock( &busy_lock );
               t2 = get_millis();
     
               busy_rate = busy_count * 1000 / (t2 - t1);
     
               if (busy_rate > max_busy)
                    max_busy = busy_rate;
          }
     
          printf( "Calibrating done. (%d busy counts/sec)\n", max_busy );
     }

     ret = fusion_enter( -1, 23, FER_MASTER, &world );
     if (ret)
          return ret;

     ret = fusion_call_init( &call, call_handler, NULL, world );
     if (ret)
          return ret;

     ret = fusion_shm_pool_create( world, "Stream Buffer", block_size + 8192, false, &pool );
     if (ret)
          return ret;

     ret = fusion_shm_pool_allocate( pool, block_size, false, true, &buffer );
     if (ret)
          return ret;



     /*
      * Do the fork() magic!
      */
     if (do_fork) {
          fusion_world_set_fork_action( world, FFA_FORK );

          switch (fork()) {
               case -1:
                    D_PERROR( "fork() failed!\n" );
                    return -1;

               case 0:
                    /* child continues as the producer */
                    run_busy = false;
                    break;

               default:
                    /* parent is the consumer (callback in Fusion Dispatch thread) */
                    produce = false;

                    usleep( 50000 );
          }

          fusion_world_set_fork_action( world, FFA_CLOSE );
     }


     start = t1 = get_millis();

     if (run_busy) {
          busy_count = 0;
          pthread_mutex_unlock( &busy_lock );
     }

#ifdef LINUX_2_4
     delay -= 10000;
#endif

     do {
          if (bit_rate || !produce) {
               if (delay > 10)
                    usleep( delay );
          }

          if (produce) {
               for (i=0; i<num_blocks; i++) {
                    int  n;
                    u32  retsum;
                    u32 *values = buffer;

                    for (n=0; n<block_size/4; n++) {
                         values[n] = n;
                         checksum += n;
                    }

                    bytes += block_size;

                    fusion_call_execute( &call, do_thread ? FCEF_NODIRECT : FCEF_NONE,
                                         0, buffer, (int*) &retsum );

                    if (retsum != checksum)
                         D_ERROR( "Checksum returned by consumer (0x%08x) does not match 0x%08x!\n", retsum, checksum );
               }

               blocks += num_blocks;
          }


          t2 = get_millis();
          if (t2 - t1 > 2000) {
               if (produce) {
                    long long kbits = 0, avgkbits, total_time, diff_time, diff_bytes;

                    printf( "\n\n\n" );

                    total_time = t2 - start;
                    diff_time  = t2 - t1;
                    diff_bytes = bytes - last_bytes;

                    avgkbits   = (long long)bytes * 8LL * 1000LL / (long long)total_time / 1024LL;

                    if (diff_time)
                         kbits = (long long)diff_bytes * 8LL * 1000LL / (long long)diff_time / 1024LL;

                    printf( "Total Time:       %7lld ms\n", total_time );
                    printf( "Stream Size:      %7lld kb\n", bytes / 1024 );
                    printf( "Stream Rate:      %7lld kb/sec -> %lld.%03lld MBit (avg. %lld.%03lld MBit)\n",
                            kbits / 8,
                            (kbits * 1000 / 1024) / 1000, (kbits * 1000 / 1024) % 1000,
                            (avgkbits * 1000 / 1024) / 1000, (avgkbits * 1000 / 1024) % 1000 );
                    printf( "\n" );


                    if (last_bytes && bit_rate) {
                         long long diff_bytes = (bytes - last_bytes) * 1000 / (t2 - t1);
                         long long need_bytes = bit_rate * 1024 / 8;

                         if (diff_bytes) {
                              int new_blocks = (num_blocks * need_bytes + diff_bytes/2) / diff_bytes;

                              num_blocks = (new_blocks + num_blocks + 1) / 2;

                              if (num_blocks > MAX_NUM_BLOCKS)
                                   num_blocks = MAX_NUM_BLOCKS;
                         }
                    }


                    read_stat();

                    if (ftotal != ctotal && dtotal) {
                         int load, aload;

                         load  = 1000 - didle * 1000 / dtotal;
                         aload = 1000 - (cidle - fidle) * 1000 / (ctotal - ftotal);

                         printf( "Overall Stats\n" );
                         printf( "  Total Time:      %7lld ms\n", t2 - start );
                         printf( "  Block Size:      %7ld\n", block_size );
                         printf( "  Blocks/cycle:    %7ld\n", num_blocks );
                         printf( "  Blocks/second:   %7lld\n", (blocks - last_blocks) * 1000 / diff_time );
                         printf( "  Delay:           %7d\n", delay );
                         printf( "  CPU Load:        %5d.%d %% (avg. %d.%d %%)\n",
                                 load / 10, load % 10, aload / 10, aload % 10 );
                    }


                    last_bytes  = bytes;
                    last_blocks = blocks;
               }

               if (run_busy) {
                    pthread_mutex_lock( &busy_lock );

                    if (last_busy) {
                         int busy_diff;
                         int busy_rate, busy_load;
                         int abusy_rate, abusy_load;

                         busy_diff = busy_count - last_busy;
                         busy_rate = max_busy - (busy_diff * 1000 / (t2 - t1));
                         busy_load = busy_rate * 1000 / max_busy;
                         abusy_rate = max_busy - (busy_count * 1000 / (t2 - start));
                         abusy_load = abusy_rate * 1000 / max_busy;

                         printf( "  Real CPU Load:   %5d.%d %% (avg. %d.%d %%)\n",
                                 busy_load / 10, busy_load % 10,
                                 abusy_load / 10, abusy_load % 10 );
                    }

                    last_busy = busy_count;

                    pthread_mutex_unlock( &busy_lock );
               }

               t1 = t2;
          }
     } while (active > 0);


     if (run_busy) {
          busy_alive = 0;

          pthread_join( busy_thread, NULL );
     }

     return -1;
}
Ejemplo n.º 21
0
static void
poll_cpu (SpHostinfoSource *self)
{
  gchar cpu[64] = { 0 };
  glong user;
  glong sys;
  glong nice;
  glong idle;
  glong iowait;
  glong irq;
  glong softirq;
  glong steal;
  glong guest;
  glong guest_nice;
  glong user_calc;
  glong system_calc;
  glong nice_calc;
  glong idle_calc;
  glong iowait_calc;
  glong irq_calc;
  glong softirq_calc;
  glong steal_calc;
  glong guest_calc;
  glong guest_nice_calc;
  glong total;
  gchar *line;
  gint ret;
  gint id;

  if (read_stat (self))
    {
      line = self->stat_buf;

      for (gsize i = 0; self->stat_buf[i]; i++)
        {
          if (self->stat_buf[i] == '\n')
            {
              self->stat_buf[i] = '\0';

              if (strncmp (line, "cpu", 3) == 0)
                {
                  if (isdigit (line[3]))
                    {
                      CpuInfo *cpu_info;

                      user = nice = sys = idle = id = 0;
                      ret = sscanf (line, "%s %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld",
                                    cpu, &user, &nice, &sys, &idle,
                                    &iowait, &irq, &softirq, &steal, &guest, &guest_nice);
                      if (ret != 11)
                        goto next;

                      ret = sscanf(cpu, "cpu%d", &id);

                      if (ret != 1 || id < 0 || id >= self->n_cpu)
                        goto next;

                      cpu_info = &g_array_index (self->cpu_info, CpuInfo, id);

                      user_calc = user - cpu_info->last_user;
                      nice_calc = nice - cpu_info->last_nice;
                      system_calc = sys - cpu_info->last_system;
                      idle_calc = idle - cpu_info->last_idle;
                      iowait_calc = iowait - cpu_info->last_iowait;
                      irq_calc = irq - cpu_info->last_irq;
                      softirq_calc = softirq - cpu_info->last_softirq;
                      steal_calc = steal - cpu_info->last_steal;
                      guest_calc = guest - cpu_info->last_guest;
                      guest_nice_calc = guest_nice - cpu_info->last_guest_nice;

                      total = user_calc + nice_calc + system_calc + idle_calc + iowait_calc + irq_calc + softirq_calc + steal_calc + guest_calc + guest_nice_calc;
                      cpu_info->total = ((total - idle_calc) / (gdouble)total) * 100.0;

                      cpu_info->last_user = user;
                      cpu_info->last_nice = nice;
                      cpu_info->last_idle = idle;
                      cpu_info->last_system = sys;
                      cpu_info->last_iowait = iowait;
                      cpu_info->last_irq = irq;
                      cpu_info->last_softirq = softirq;
                      cpu_info->last_steal = steal;
                      cpu_info->last_guest = guest;
                      cpu_info->last_guest_nice = guest_nice;
                    }
                }
              else
                {
                  /* CPU info comes first. Skip further lines. */
                  break;
                }

            next:
              line = &self->stat_buf[i + 1];
            }
        }
    }
}
Ejemplo n.º 22
0
static void read_procs(void) {
    DIR *proc_dir, *task_dir;
    struct dirent *pid_dir, *tid_dir;
    char filename[64];
    FILE *file;
    int proc_num;
    struct proc_info *proc;
    pid_t pid, tid;

    int i;

    proc_dir = opendir("/proc");
    if (!proc_dir) die("Could not open /proc.\n");

    new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
    num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);

    file = fopen("/proc/stat", "r");
    if (!file) die("Could not open /proc/stat.\n");
    fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
            &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
    fclose(file);

    proc_num = 0;
    while ((pid_dir = readdir(proc_dir))) {
        if (!isdigit(pid_dir->d_name[0]))
            continue;

        pid = atoi(pid_dir->d_name);
        
        struct proc_info cur_proc;
        
        if (!threads) {
            proc = alloc_proc();

            proc->pid = proc->tid = pid;

            sprintf(filename, "/proc/%d/stat", pid);
            read_stat(filename, proc);

            sprintf(filename, "/proc/%d/cmdline", pid);
            read_cmdline(filename, proc);

            sprintf(filename, "/proc/%d/status", pid);
            read_status(filename, proc);

            read_policy(pid, proc);

            proc->num_threads = 0;
        } else {
            sprintf(filename, "/proc/%d/cmdline", pid);
            read_cmdline(filename, &cur_proc);

            sprintf(filename, "/proc/%d/status", pid);
            read_status(filename, &cur_proc);
            
            proc = NULL;
        }

        sprintf(filename, "/proc/%d/task", pid);
        task_dir = opendir(filename);
        if (!task_dir) continue;

        while ((tid_dir = readdir(task_dir))) {
            if (!isdigit(tid_dir->d_name[0]))
                continue;

            if (threads) {
                tid = atoi(tid_dir->d_name);

                proc = alloc_proc();

                proc->pid = pid; proc->tid = tid;

                sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
                read_stat(filename, proc);

                read_policy(tid, proc);

                strcpy(proc->name, cur_proc.name);
                proc->uid = cur_proc.uid;
                proc->gid = cur_proc.gid;

                add_proc(proc_num++, proc);
            } else {
                proc->num_threads++;
            }
        }

        closedir(task_dir);
        
        if (!threads)
            add_proc(proc_num++, proc);
    }

    for (i = proc_num; i < num_new_procs; i++)
        new_procs[i] = NULL;

    closedir(proc_dir);
}