小默

gcc math.h -lm

程序中用到 math.c,使用 gcc 编译,需要加上 -lm 选项。
-l表示使用库,m为数学库。
=================
Linux程序设计中的一个例子:
#include <sys/types.h>
#include 
<sys/resource.h>
#include 
<sys/time.h>
#include 
<unistd.h>
#include 
<stdio.h>
#include 
<math.h>

/// 向一个临时文件写一个字符串10000次,然后进行一些数学运算,目的是制造一些CPU负荷
void work()
{
    FILE 
*f;
    
int i;
    
double x = 4.5;

    f 
= tmpfile(); // 创建临时文件
    for(i = 0; i < 10000; i++){
        fprintf(f, 
"Do some output\n");
        
if(ferror(f)){ //TODO ferror?
            fprintf(stderr, "Error writing to temporary file\n");
            exit(
1);
        }
    }

    
for(i = 0; i < 1000000; i++)
        x 
= log(x*+ 3.21);
}

/// main 函数先调用 work, 再调用 getrusage 函数查看它使用了多少 CPU 时间。把这些资料显示在屏幕上。
int main()
{
    
struct rusage r_usage;
    
struct rlimit r_limit;
    
int priority;

    work();
    getrusage(RUSAGE_SELF, 
&r_usage); // 只返回当前程序的 CPU 占用时间

    printf(
"CPU usage: User = %ld.%06ld, System = %ld.%06ld\n",
           r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,    
// r_usage.ru_utime 程序本身执行它的指令所消耗的时间
           r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);   // r_usage.ru_stime OS由于这个程序而消耗的 CPU 时间

    
/// 调用 getpriority 和 getrlimit 函数分别查出自己的当前优先级和文件长度限制
    priority = getpriority(PRIO_PROCESS, getpid()); // PRIO_PROCESS 表示后面是进程标识符
    printf("Current priority = %d\n", priority);
    getrlimit(RLIMIT_FSIZE, 
&r_limit); // 读取以字节计的文件长度限制到 r_limit 中
    printf("Current FSIZE limit: soft = %ld, hard = %ld\n",
              r_limit.rlim_cur, r_limit.rlim_max);  
// rlim_cur 软限制, rlimt_max 硬限制

    
/// 通过 setrlimit 函数设置了一个文件长度限制。
    r_limit.rlim_cur = 2048;    // 软限制2M
    r_limit.rlim_max = 4096;    // 硬限制4M
    printf("Setting a 2K file size limit\n");
    setrlimit(RLIMIT_FSIZE, 
&r_limit);

    
/// 然后再次调用 work 失败,因为它尝试创建的文件尺寸过大。
    work();

    exit(
0);

}

编译:
[green@colorfulgreen environ]$ gcc limits.c -o limits

报错:
/tmp/ccxW94yi.o: In function `work':
limits.c:(.text+0xaf): undefined reference to `log'
collect2: ld returned 1 exit status

编译时加上 -lm 选项:
[green@colorfulgreen environ]$ gcc limits.c -lm -o limits

Done.
============
PS:为嘛这个编辑器插入代码时最前面不能有下面这几行T_T
/**
  * 资源限制
**/






posted on 2010-08-05 09:04 小默 阅读(1580) 评论(0)  编辑 收藏 引用 所属分类: Linux


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

留言簿(13)

随笔分类(287)

随笔档案(289)

漏洞

搜索

积分与排名

最新评论

阅读排行榜