我需要在定义的时间间隔内运行子进程。 exec()之后的wait()弄乱了时间。如何在不冻结执行/搞乱时间的情况下从子节点获取返回值?如果这不可能或非常难,那么我如何在不离开僵尸的情况下丢弃返回值?
示例代码: (目标是以10秒的间隔运行所有作业[])
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<unistd.h>
#include<sys/types.h>
main() {
int i, status;
char jobs[3][100+1];
time_t t;
pid_t pid;
strncpy(jobs[0], "sleep 3", 100);
strncpy(jobs[1], "sleep 5", 100);
strncpy(jobs[2], "sleep 10", 100);
while (1) {
t = time(NULL);
sleep(5 - t % 5);
printf("executing jobs. time: %s", ctime(&t));
for (i = 0; i < 3; i++) {
t = time(NULL);
pid = fork();
if (pid == 0) {
printf("run: %s, pid %d, time: %s\n", jobs[i], (int) getpid(), ctime(&t));
execl("/bin/sh", "/bin/sh", "-c", jobs[i], (char *) NULL);
}
}
while ((pid = wait(&status)) > 0) {
t = time(NULL);
printf("job complete. pid: %d, return: %d, time: %s\n", (int) pid, status, ctime(&t));
}
t = time(NULL);
printf("done. time: %s", ctime(&t));
sleep(10);
}
}