如何在使用睡眠功能,你增加一个计数? [英] How do you increment a count while using the sleep function?

查看:137
本文介绍了如何在使用睡眠功能,你增加一个计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我似乎丢失。我应该能够在子递增无限循环内的计数,并有计数被打印的每个父发送一个信号,该信号应该是每隔1秒的时间。我写我的code,但我认为,用叉后,孩子与父进程同时运行,但事实却不是这样,我不知道如何解决这个问题的情况。任何帮助将是巨大的。

Hey guys I seem to be lost. I am supposed to be able to increment a count in a child inside an infinite loop, and to have the count be printed every time the parent sends a signal, which should be every 1 second. I wrote my code but I thought that after using fork, the child and parent processes run at the same time, however this is not the case so I'm not sure how to tackle this problem. Any help would be great

推荐答案

你所描述应该在理论上都是些什么。

What you are describing should work in theory.

编写并行code可能会非常棘手,尤其是在使用叉(),如果你不熟悉的过程。

Writing parallel code can be tricky, especially using fork(), if you're not familiar with the process.

下面是我的建议:添加了一堆调试打印整个code,例如:

Here is my suggestion: add a bunch of debug prints throughout your code, for example:

int pid = fork();
if(pid == -1) {
    printf("Fork failed!\n");
} else if (pid) {
    printf("I'm the parent!\n");
    // Do stuff
    printf("Parent exiting\n");
    exit(0);
} else {
    printf("I'm the child!\n");
    // Do stuff
    printf("Child exiting\n");
    exit(0);
}

这时你可以看到,如果你的程序行为的方式应该。

Then you can see if your program is behaving the way it should.

还添加了一个的printf()语句信号处理程序,因此您可以确保它被调用。

Also add a printf() statement to your signal handler so you can make sure it is being called.

这篇关于如何在使用睡眠功能,你增加一个计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆