How do you increment a count while using the sleep function?

我与影子孤独终老i 提交于 2020-01-04 06:51:13

问题


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


回答1:


What you are describing should work in theory.

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

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.

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




回答2:


The child process should be able to just run sleep(), and have the parent send SIGALRM to wake it up. Perhaps you made the child sit in a busy loop, consuming so much CPU that the parent didn't get to run as predicted.

Of course, answers to questions like these are way better if you show your code.



来源:https://stackoverflow.com/questions/10328956/how-do-you-increment-a-count-while-using-the-sleep-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!