2010-04-21 198 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;