C – fork()和共享内存

我需要我的父进程和子进程才能读取和写入相同的变量(类型为int),因此它在两个进程之间是“全局的”。

我假设这会使用某种跨进程通信,并且在一个进程上有一个变量正在更新。

我做了一个快速谷歌和IPC和各种技术出现,但我不知道哪个是最适合我的情况。

那么什么技术是最好的,你可以提供一个链接到它的noobs教程。

谢谢。

既然你提到使用fork(),我假设你生活在一个* nix-System上

来自Unix.com

使用UNIX IPC在进程之间共享数据的主要方法是:

(1)共享记忆;

(2)sockets:

还有其他UNIX IPC包括

(3)消息队列。

(4)信号量;

(5)信号。

你最好的选择(对于IPC)是根据你的post使用共享内存段。 您可能需要使用信号量来确保共享内存操作是primefaces的。

关于分叉和共享内存的教程正在开发中:

http://forums.devshed.com/c-programming-42/posix-semaphore-example-using-fork-and-shared-memory-330419.html

关于使用multithreading的另一个更深入的描述(如果适用于您的应用程序)可以在这里找到:

https://computing.llnl.gov/tutorials/pthreads/

如果你需要共享内存,也许使用线程而不是进程是一个更好的解决方案?

我最近使用共享内存的一个变体是在分叉之前打开一个mmap。 这避免了共享内存api的某些限制。 您没有大小限制(地址范围是限制),您不需要从该绝对文件生成密钥。 这是我如何做到的一个例子(为了简洁,我省略了错误检查)

ppid = getpid(); shm_size = ...; char *tmpFile = tempnam(NULL, "SHM_"); /* Generate a temp file which is virtual */ /* Before we fork, build the communication memory maps */ mm = open(tmpFile, O_RDWR|O_CREAT|O_TRUNC, 0664)); /* Create the temp file */ ftruncate(mm, shm_size); /* Size the file to the needed size, on modern Unices it's */ /* a sparse file which doesn't allocate anything in the file system */ /* The exact type of comm_area left to the implementer */ comm_area *pCom = (comm_area *)mmap(NULL, shm_size, PROT_READ|PROT_WRITE, MAP_SHARED, mm, 0); if(pCom == (comm_area*)MAP_FAILED) handle_error(); close(mm); /* We can close the file, we won't access it via handle */ unlink(tmpFile); /* We can also remove the file so even if we crash we won't let corpses lying */ free(tmpFile); /* Initialise some shared mutexes and semaphores */ pthread_mutexattr_t mattr; pthread_mutexattr_init(&mattr); pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&pCom->stderr_mutex, &mattr); /* nSonAsked, global variable with the number of forked processes asked */ for(nSon=0; nSonsem_ch[nSon], USYNC_PROCESS, 0); if(fork() == 0 { ... /* do child stuff*/ return; } /* Father, cleans up */ pthread_mutexattr_destroy(&mattr); ... return;