GCC fork() - Can a child change a parent variable?
Here is are pieces of my code:
Code:
<includes> ... So is it possible to change the int variable turn using the child process or there might be some other bad thing I am doing? *Cheers |
sorry, i cant answer your question, but i noticed the following mistake.
if(!fork()) { recv_msg("1"); } should be if(!fork()) { recv_msg('1'); } |
No, it shouldn't. If you look at the signature of his recv_msg() function it expects one parameter of type pointer-to-char (should really be const char *), not just a char.
|
I'm no expert on forking, but as I understand it, when you fork, you create an entirely new process (complete with its own distinct memory space). Therefore, and attempts to modify variables would modify the variables in the new process's memory space. Provided that's true, then the only way you could have the fork'ed process modify the original process's variables would be to pass a pointer to the memory of the original process. You could do that with a file, a pipe, or perhaps some other mechanism.
|
Quote:
One thing you should watch out for with fork() is that you make sure the child process exits when it's supposed to. In your code it looks like the child will fall out of the if statement and begin executing the same code that the parent is supposed to. (You can fix this by having it exit() appropriately.) |
All times are GMT -5. The time now is 05:36 AM. |