问题
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