1

我们使用getrusage()系统调用来查找不同的资源值,它需要两个参数,其中第一个参数是RUSAGE_SELFRUSAGE_CHILDREN,另一个参数是一个名为rusage的结构。这个结构有许多可以访问并给出值的元素,但是所有这些元素代表什么?

#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>

void print_cpu_time()
{
 struct rusage usage;
 getrusage (RUSAGE_SELF, &usage);
 printf ("CPU time: %ld.%06ld sec user, %ld.%06ld sec system\n",
     usage.ru_utime.tv_sec, usage.ru_utime.tv_usec,
     usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
}

int main()
{
    print_cpu_time();
} 

该程序显示用户时间和系统时间的值。

结构的其他元素代表什么以及如何在实际程序中使用它们,例如,如果我试图访问它们,我将获得所有其他结构元素的值 0。那么如何使用它们来获得 0 以外的值呢?

编辑:我编写了一个程序来查找 ru_inblock 和 ru_oublock 的值。对于任何给定的输入,对于 ru_inblock 和 ru_oublock 的输出为 0 和 8。为什么会这样?代码如下

#include <stdio.h>
#include <sys/resource.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

// a struct to read and write 
struct person 
{ 
  int id; 
  char fname[20]; 
  char lname[20]; 
}; 

int main () 
{ 
  FILE *outfile; 
  char ch;
  struct person Stu;
int r;

  outfile = fopen ("student.dat", "w"); 
  if (outfile == NULL) 
  { 
    fprintf(stderr, "\nError opened file\n"); 
    exit (1); 
  } 
   do
              {
                      printf("\nEnter Roll : ");
                      scanf("%d",&Stu.id);
                      scanf("%*c");
                      printf("Enter First Name : ");
                      scanf("%s",Stu.fname);
                      scanf("%*c");
                      printf("Enter Last Name : ");
                      scanf("%s",Stu.lname);

                      fwrite(&Stu,sizeof(Stu),1,outfile);

                      printf("\nDo you want to add another data (y/n) : ");
                      scanf("%*c");
                      ch = getchar();


              }
            while(ch=='y' || ch == 'Y');



  if(fwrite != 0) 
    printf("contents to file written successfully !\n"); 
  else
    printf("error writing file !\n"); 
 fclose (outfile); 

 outfile = fopen ("student.dat", "r"); 
  if (outfile == NULL) 
  { 
    fprintf(stderr, "\nError opened file\n"); 
    exit (1); 
  } 

  struct person input; 

  while(fread(&input, sizeof(struct person), 1, outfile)) 
        printf ("id = %d name = %s %s\n", input.id, 
        input.fname, input.lname); 


 fclose (outfile);

  struct rusage r_usage;

  r=getrusage(RUSAGE_SELF,&r_usage);
  printf("\n%d\n",r);
  printf("Memory usage = %ld\n",r_usage.ru_maxrss);
  printf("\ninput operations : %ld \n", r_usage.ru_inblock);
  printf("\noutput operations : %ld \n", r_usage.ru_oublock);


  return 0; 
} 
4

0 回答 0