how to retain changes made in a global variable by a child process after in exits
I want to retain changes made by a child process in a variable after the child process exits.Consider following program
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> volatile int i=0; void child(){ i++; printf("i in child is %d \n",i); kill(getpid(),SIGKILL); } int main() { pid_t pid; printf("fork program starting\n"); pid = fork(); if (pid==0) child(); else wait(NULL); printf("i in parent is %d \n",i); } it gives output : fork program starting i in child is 1 i in parent is 0 but I want that i,after execution of child process (which made it 1) remains 1. Is there a way of doing it? |
My C programming skill aren't the greatest, but I see things which do not conform to what I was taught.
Code:
#include <sys/types.h> Code:
void child(){ Code:
#include <sys/types.h> Now you need to finish the correction to use the return value. |
thanx for replying, Mr. bigrigdriver.
C allows(as per my knowledge) function definition before main() in which case you need not declare the prototype. void functions are also syntactically correct.Did u notice the kill() in child? it actually kills the child process. then what would it return? For example, try following: int child(){ i++; printf("i in child is %d \n",i); kill(getpid(),SIGKILL); printf("child not died"); return i; } You ll never see "child not died". So, its expected that return statement is also not executed. This doesnot solve the problem. Probably u had a misunderstanding with my question.Suppose a child process modifies a global variable. What I am getting is that after the child dies, change in that variable is not retained, which is unlike the case that when the living process modifies it, global variable change is retained.Comment out the if and else statement in main(). You ll see the difference. |
In short you can't. Once you fork, you are running 2 separate processes.
You can use various mechanisms to get around this eg shared mem, or threads or a temp file, or even proc-to-proc comms via a pipe or socket. This area is known as IPC (Inter Process Communication). |
All times are GMT -5. The time now is 05:31 AM. |