0

我在看《unix环境高级语言编程》的时候对第八章图8-30的代码的关于timeval的使用不太了解,希望能有大佬能帮忙解释一下谢谢

#include "apue.h"
#include <errno.h>
#include <sys/time.h>

#if defined(MACOS)
#include <sys/syslimits.h>
#elif defined(SOLARIS)
#include <limits.h>
#elif defined(BSD)
#include <sys/param.h>
#endif

unsigned long long count;
struct timeval end;

void checktime(char* str){
    struct timeval tv;
    gettimeofday(&tv,NULL);
    if(tv.tv_sec>=end.tv_sec&& tv.tv_usec>=end.tv_usec){
        printf("%s count =%lld\n",str,count);
        exit(0);
    }
}

int main(int argc,char* argv[]){
    pid_t pid;
    char* s;
    int nzero,ret;
    int adj=0;

    setbuf(stdout,NULL);

#if defined(NZERO)
    nzero=NZERO;
#elif defined(_SC_NZERO)
    nzero=sysconf(_SC_NZERO);
#else
#error NZERO undefined
#if
    printf("NZERO =%d\n",nzero);
    if(argc==2)
        adj=strtol(argv[1],NULL,10);
    gettimeofday(&end,NULL);//
    end.tv_sec+=10;//

    if((pid=fork())<0)
        err_sys("fork error");
    else if(pid==0){
        s="child";
        printf("current nice value in child is %d,adjusting by%d\n",
                nice(0)+nzero,adj);
        errno=0;
        if((ret=nice(adj))==-1&&errno!=0)
            err_sys("child set scheduing priority");
        printf("now child nice value is %d\n",ret+nzero);
    }else{
        s="parent";
        printf("current nice value in %s is %d,adjusting by%d\n",
                s,nice(0)+nzero,adj);
    }
    for(;;){
        if(++count==0)
            err_quit("%s counter wrap",s);
        checktime(s);
    }
}



我看注释的意思是+=10是运行十秒钟,这个操作我不是很明白,查timeval也没有比较相似的例子,希望有大佬帮忙解释一下谢谢

2019-05-28 提问
1 个回答
1

已采纳

gettimeofday获取当前时刻保存到end变量

并不是 += 10 表示运行10s,运行10s肯定是你后面的代码用到了end的地方

struct timeval{

  __time_t tv_sec;       /* Seconds */
  __suseconds_t tc_usec; /* Microseconds */
}

撰写答案

推广链接