2010-04-21 256 views
12

我需要我的父進程和子進程都能夠讀寫同一個變量(類型爲int),因此它在兩個進程之間是「全局的」。C-fork()和共享內存

我假設這會使用某種跨進程通信,並且在更新一個進程時有一個變量。

我做了一個快速谷歌和IPC和各種技術來了,但我不知道哪個是最適合我的情況。

那麼什麼技術是最好的,你可以提供一個鏈接到它的noobs教程。

謝謝。

回答

15

由於使用fork()的提,我認爲你是生活在* nix系統內

Unix.com

共享使用UNIX IPC經過 進程之間數據的主要方式:

(1)共享內存;

(2)套接字:

還有其他的UNIX的IPC包括

(3)消息隊列。

(4)信號量;

(5)信號。

根據您的 的帖子,您最好的選擇(對於IPC)是使用 共享內存段。您可能需要使用信號量 來確保共享內存 操作是原子操作。

上分叉的指南和共享存儲器是dev的棚:

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

另一個更深入的使用多線程(如果appilcable爲應用程序)的描述可以在這裏找到:

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

+0

最後帶共享內存。 – Cheetah 2010-04-22 20:15:25

+2

這裏可疑的類似文本(你可能想鏈接信用?):http://www.unix.com/programming/857-fork-ipc。html – sje397 2011-05-24 06:08:02

+0

@ sje397:謝謝你指出我引用失敗 – sum1stolemyname 2011-06-10 08:33:18

4

如果你需要共享內存,也許使用線程而不是進程將是一個更好的解決方案?

+0

它是大學的一項任務。你必須使用fork(),特別是 – Cheetah 2010-04-21 12:02:18

2

我最近使用的共享內存的一個變種是在分叉之前打開一個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; nSon<nSonsAsked; nSon++) { 

    printf("Setup son #%.2u ",nSon+1); 
    /* Initialize a semaphore for each child process */ 
    sem_init(&pCom->sem_ch[nSon], USYNC_PROCESS, 0); 
    if(fork() == 0 { 
    ... /* do child stuff*/ 
    return; 
    } 
    /* Father, cleans up */ 
    pthread_mutexattr_destroy(&mattr); 
    ... 
    return;