求助,fork函数建立子进程后,如何让子进程和父进程共享一个变量
如程序,为什么指针相同,但是所指的值不相同?
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int j = 0;
/*
*
*/
int main(int argc, char** argv) {
signal(SIGCHLD,SIG_IGN); //avoid zombie process
int *i;
i = &j;
int k=0;
pid_t pid,pid1,pid2;
cout < <"this is at beginning, pointer i is" < <i < <endl;
sleep(1);
pid = fork();
if(pid <0)
{
cout < <"create childprocess error!" < <endl;
}
else if (pid == 0)
{
cout < <"for childprocess,pointer i = " < <i < <endl;
for(k;k <10;k++)
{
(*i)++;
cout < <"for childprocess,j = " < <*i < <endl;
}
}
else if(pid > 0)
{
sleep(5);
cout < <"for fatherprocess, j = " < <*i < <endl;
cout < <"for fatherprocess, i = " < <i < <endl;
}
return (EXIT_SUCCESS);
}
输出:
this is at beginning, pointer i is0x804a0d4
for childprocess,pointer i = 0x804a0d4
for childprocess,j = 1
for childprocess,j = 2
for childprocess,j = 3
for childprocess,j = 4
for childprocess,j = 5
for childprocess,j = 6
for childprocess,j = 7
for childprocess,j = 8
for childprocess,j = 9
for childprocess,j = 10
for fatherprocess, j = 0
for fatherprocess, i = 0x804a0d4
为什么呢?i虽然被fork复制了,但是i的值一直没有改变,所以它指向的值应该是同一个值才对阿。
而无论子进程还是父进程对*i进行任何操作也应该都应该对j产生影响。
除了共享内存,还有什么办法能fork函数建立子进程后,让子进程和父进程共享一个变量j?