我有一个“理论”问题需要解决,
我有一个用x参数执行的CTRL程序(./CTRL X1 X2 XN)。
x中的每一个都是一个要执行的程序,所有这些程序都给标准输出“ok”,表明它每3秒生存一次。如果CTRL程序没有收到“ok”,它应该终止x程序并打印它执行的时间。
当它们全部完成时,CTRL结束。
我管理(我认为)创建x程序,管道和重定向,但是,我如何检查它每3秒获得一次响应并计算它?
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
int r,i;
int pn = argc;
int filhos[pn];
int fd[pn][2];
int time[pn][1];
//start the pn process and redirect from stdout do pipe
for (i=1 ; i<=pn;i++;) {
r=fork();
filhos[i] = getpid();
pipe(fd[i]);
if (r==0) {
close(fd[i][0]);
dup2(fd[i][1],1); //redirect stdout to pipe
close(fd[i][1]);
execlp(argv[i],argv[i],NULL);
}
else {
//how to check every 3s to confirm its printing the "ok" ?
open(fd[i][0]);
wait(status); //should be a while(1) ?
//check if its receiving the "ok" and kill the process if not
kill(filhos[i],SIGUSR1);
//print the time it took - how to now the time passed?
printf("process %s has terminated over %i seconds",argv[i],time[i]);
}
}
//when all of them stops
return 0;
}
编辑:
好的,为了得到时间,我可以使用
time_t start_t, end_t;
double diff_t;
time(&start_t);
time(&end_t);
diff_t = difftime(end_t, start_t);