c - 在 C 中运行一个任务 N 秒

标签 c timer process

我正在尝试完成大学作业,但遇到了问题。我想为我的程序创建一个类似“计时器”的东西。我的意思是我想运行该程序 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/

相关文章:

c - 线程要处理

c - 当我在 linux 下的 c 套接字中使用 read() 和 write() 时尺寸缩小

非常基本的 C 程序上的 C 编程 EXC_BAD_ACCESS

c# - Unity3d 后台实时计数器

c# - System.Timers.Timer 设置为 24 小时间隔

Linux进程和线程调度

c - C中如何判断用户在命令行输入 "*"表示多个文件

c - 在 C 中将文件内容打印到标准输出低级 I/O

c++ - boost 定时器 : how to get time when I need?

python - 为什么我们应该在 subprocess.Popen 中使用 stdout=PIPE?