C - sharing variables between forked processes?
my program forks early on and each process runs a looping function.
I want one function to set the value of 'int range' and the other function in another process to change based on the value of range set by the first function. i have something like this: int range; int loop_A() { while(1) { } } int loop_B() { while(1) { } } int loop_1() { while(1) { range = gpa_read(0); /* gets a distance reading from a sensor */ } } int loop_2() { while(1) { if(range == 0) { loop_A(); } if(range > 0) { loop_B(); } } } int main() { pid_t pid; pid = fork(); int proc_val; switch(pid) { case 0: proc_val = 0; break; case 1: proc_val = 1; break; } if(proc_val == 0) { loop_1(); } else { loop_2(); } } /* end code */ but loop_2() never seems to change. how do i define vars to be accessable across all processes? thanks |
When the processes fork any global variables are passed but if you change the value of that variable in the forked process the change is only visible to the process that changed it.
It sounds to me like you should be looking at a threaded solution since threads can share variables but you will need to use semaphors or some equivalent to protect the variable from multiple concurrent writes to it. Your other solution will be to use pipes between your processes, this would be more difficult to maintain than using threads. |
gonna give it a try using threads.
Thanks |
awesome it's working great. I managed to get it going without semaphore because there is only one thread that will write to a variable while all the others are only reading.
thanks again |
i suggest you read this: http://www.ecst.csuchico.edu/~beej/guide/ipc/
there are plenty of ways to share values before processes. |
BTW, the case statements in your 'switch(pid)' are incorrect. 0 is returned by fork() in the parent process (which you have correct), but it will almost certainly never return 1 for the child process. So proc_val will never be 1 and loop_2() will never run.
Might wanna try something like this instead: Code:
pid = fork(); |
All times are GMT -5. The time now is 10:00 PM. |