我正在尝试完成大学作业,但遇到了问题。我想为我的程序创建一个类似“计时器”的东西。我的意思是我想运行该程序 30 秒,之后我想在关闭它之前打印一些统计信息。由于它是一个与流程相关的项目,如果可能的话,我希望也将这个计时器传递给子流程。这是我想要完成的一些伪代码。
/* Timer starts from here */
- forking childs
- child execute
- other actions
/* Timer finishes here */
Printing statistics
exit(0)
我尝试阅读有关闹钟、时间和其他内容的内容,但找不到任何可以帮助我的内容。希望您能帮助我并提前致谢。
最佳答案
尝试阅读 alarm()
的手册页。检查alarm
的手册页
unsigned int alarm(unsigned int seconds);
返回什么警报? alarm() 返回任何先前安排的警报到期之前剩余的秒数,如果有则返回零 之前没有安排闹钟。
您可以将多个 alarm()
设置为 N
秒,但不能一次全部设置。
这是理解alarm()的简单代码。
#include<signal.h>
#include<stdio.h>
int al = 5;
void my_isr(int n)
{
static int count = 0;//count variable
if(n == 17) {
/** this child will execute if child completer before 5 seconds**/
int ret = wait(0);//releases child resources
printf("child %d completed \n",ret);
}
if(n == 14) {
printf("in sigalarm isr \n");
/** do task here **/
if(count<3) {
alarm(5);// after doing some task set another alarm
}
count++;
}
}
int main()
{
if(fork()==0)
{
printf("child : pid = %d ppid = %d\n",getpid(),getppid());
/** letting the child to run for 20 seconds **/
sleep(20);
printf("child exits after task over \n");
exit(0);
}
else
{
alarm(al);//setting 5 seconds timer for child to finish job
signal(SIGALRM,my_isr);
/** to avoid child to become zombie. when child completes parents will receive SIGCHLD signal, upon receving this parent needs to free the resources associated with it using wait */
signal(SIGCHLD,my_isr);
while(1);//to keep main process alive for observation
}
}
希望对你有帮助。
关于c - 在 C 中运行一个任务 N 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47797903/