23,121
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/resource.h>
void runme(){
if(freopen("out.txt","w",stdout)==NULL)
printf("redirecting error");
if(freopen("in.txt","r",stdin)==NULL)
printf("redirecting error");
execl("./normal","./normal",(char *)NULL);
int i;
for(i=0;i<10000000000;i++) (void)getppid();
fclose(stdout);
fclose(stdin);
//retuen 0;
}
int main(){
int status;
struct rusage ruse;
int usedtime=0;
pid_t tpid;
switch(tpid = fork()){
case -1:printf("open pid error\n");exit(-1);
case 0:
printf("open child\n");
runme();
exit(0);
default:
printf("father, child pid is %d \n", tpid);
printf("waited child's pid is %d \n",wait4(tpid, &status, WUNTRACED, &ruse));
usedtime += (ruse.ru_utime.tv_sec * 1000 + ruse.ru_utime.tv_usec / 1000);
usedtime += (ruse.ru_stime.tv_sec * 1000 + ruse.ru_stime.tv_usec / 1000);
}
printf("%d\n%d\n%d\n%d\n",ruse.ru_utime.tv_sec,ruse.ru_utime.tv_usec,ruse.ru_stime.tv_sec,ruse.ru_stime.tv_usec);
printf("total time is %d ms", usedtime);
return 0;
}
printf("%d\n%d\n%d\n%d\n",ruse.ru_utime.tv_sec,ruse.ru_utime.tv_usec,ruse.ru_stime.tv_sec,ruse.ru_stime.tv_usec);
But the answers are still zero. That's what I didn't understand.
Thank you every much for your help all the same. Is there something we didn't noticed? I have struggled one day in this problem...
And forgive my English.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/resource.h>
void runme(){
if(freopen("./out.txt","w",stdout)==NULL)
printf("redirecting error");
if(freopen("./in.txt","r",stdin)==NULL)
printf("redirecting error");
//execl("./normal","./normal",(char *)NULL);
system("./normal");
//int i;
//for(i=0;i<10000000000;i++) (void)getppid();
fclose(stdout);
fclose(stdin);
exit(0);
}
int main(){
int status;
struct rusage ruse;
int usedtime=0;
pid_t tpid;
switch(tpid = fork()){
case -1:printf("open pid error\n");exit(-1);
case 0:
printf("open child\n");
runme();
//exit(0);
default:
printf("father, child pid is %d \n", tpid);
printf("waited child's pid is %d \n",wait4(tpid, &status, WUNTRACED, &ruse));
usedtime += (ruse.ru_utime.tv_sec * 1000 + ruse.ru_utime.tv_usec / 1000);
usedtime += (ruse.ru_stime.tv_sec * 1000 + ruse.ru_stime.tv_usec / 1000);
}
printf("%d\n%d\n%d\n%d\n",ruse.ru_utime.tv_sec,ruse.ru_utime.tv_usec,ruse.ru_stime.tv_sec,ruse.ru_stime.tv_usec);
printf("total time is %d ms", usedtime);
return 0;
}