Reputation: 69
I'd like to have a shared memory between processes to keep PID's.
I created global array of pid_t type and using fork created new process where I changed value of array's element.
Why the array at parent process is unchanged if array is pointing at the same?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
pid_t p[1];
int main ()
{
pid_t f;
f = fork();
if(f == 0)
{
p[0] = getpid();
printf("Child ... p[0] PID = %d\n", (int)p[0]);
printf("points at %ld\n", (long int)p);
}
else if (f > 0)
{
sleep(1);
printf("Parent... p[0] PID = %d\n", (int)p[0]);
printf("points at %ld\n", (long int)p);
}
else
{
printf("Fork() error \n");
exit(1);
}
}
Upvotes: 0
Views: 1991
Reputation: 41
Processes created by fork() do not share memory. The new process that's created gets copies of things in the parent process, not references to existing data. In fact, the child runs in a completely different address space from the parent. Thus your p[] array is a different array in the child so modifying it does not change it in the parent.
If you want to share memory between processes you create with fork(), you can use pipe() to send data one-way, mmap() to map a region of shared memory, or use another IPC mechanism available in your OS. Generally speaking if you really need to share memory you are better off using threads rather than processes.
As an aside: using sleep() is not always reliable to ensure that an event (in this case, modifying p[]) has happened. You may want to use one of the wait() family of functions in the parent which will cause the parent to block until the child exits.
Upvotes: 1