我试图在C方案拟订中履行(......)职能。
I m using the struct tms
structure which consists of the fields: tms_utime, tms_cutime,
tms_stime and tms_cstime.
为了在我的节目中履行职能,我确实:
Before I fork and create a child, I call the times function (in the parent process).
times(&start_tms);
- I create a pipe and I pass the times of start structure to the pipe when I m in the child process.
- The child executes a simple
ls -l
command 当儿童完成处决时,父亲第二次要求履行(或)职能。
times(&end_tms);
不幸的是,末端的时代是零! 我不知道为什么。
我在方案中不理解的是:
1) In the first printfs
the times of the struct start are negative. Why is that?
2) When I run the program, why do I get zeros for times? What am i doing wrong?
我的方案如下:
提前感谢
#include <sys/times.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
printf("test
");
int fd[2]; //two pointers
int nbytes;
char string[] = "Hello, world!
";
char readbuffer[80];
struct tms start_tms;
struct tms end_tms;
clock_t start, end;
double cpu_time_used;
pipe(fd);
//once we have established the pipeline we fork the child
pid_t childpid;
pid_t pid_waitpid;
//NEW MODIFICATION!!! call times before fork()!!!
times(&start_tms);
//they return negative values, but why???
printf("Test start_tms.tms_utime = %f
",start_tms.tms_utime);
printf("Test start_tms.tms_cutime = %f
",start_tms.tms_cutime);
printf("Test start_tms.tms_stime = %f
",start_tms.tms_stime);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* call times function */
/*times(&start_tms);*/
//REMOVED!!!!
//write(fd[1], string, (strlen(string)+1));
write(fd[1], &start_tms.tms_cutime, sizeof(clock_t));
write(fd[1], &start_tms.tms_utime, sizeof(clock_t));
write(fd[1], &start_tms.tms_stime, sizeof(clock_t));
//execute /bin/ls
execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* NEW MODIFICATION, wait for the child!!! */
if( (pid_waitpid = waitpid(childpid,NULL,0) ) == -1)
{
perror("waitpid");
exit(1);
}
/* call times for capturing end times */
times(&end_tms);
/* define t1, t2, variables */
clock_t t1,t2,t3;
//REMOVED!!!!
//nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
read(fd[0], &t1, sizeof(clock_t));
read(fd[0], &t2, sizeof(clock_t));
read(fd[0], &t3, sizeof(clock_t));
printf("Received string: %s
", readbuffer);
printf("Test t1 = %f
",t1);
printf("Test end_tms.tms_utime = %f
",end_tms.tms_utime);
printf("Test end_tms.tms_cutime = %f
",end_tms.tms_cutime);
printf("Test end_tms.tms_stime = %f
",end_tms.tms_stime);
/* Calculate times, unfortunately return zero, but why??? */
double cpu_time = end_tms.tms_cutime - t1;
double utime = end_tms.tms_utime - t2;
double stime = end_tms.tms_stime - t3;
//Unfortunately printfs return zero, but why???
printf("cpu time %f
",cpu_time);
printf("cpu Utime %f
",utime);
printf("cpu Stime %f
",stime);
}
}