代码之家  ›  专栏  ›  技术社区  ›  Cheetah

c-fork()和共享内存

  •  13
  • Cheetah  · 技术社区  · 16 年前

    我需要我的父进程和子进程都能够读写相同的变量(int类型),所以这两个进程之间是“全局”的。

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

    我做了一个快速的谷歌和工控机和各种技术来了,但我不知道哪一个最适合我的情况。

    所以什么技术是最好的,你能为它提供一个指向noobs教程的链接吗?

    谢谢。

    3 回复  |  直到 13 年前
        1
  •  16
  •   Jens    13 年前

    既然您提到使用fork(),我假设您生活在一个*nix系统上。

    Unix.com

    共享数据的主要方式 使用Unix IPC的进程有:

    (一)共享内存;

    (2)插座:

    其他Unix IPC包括

    (3)消息队列。

    (4)信号量;

    (5)信号。

    你最好的选择是使用 共享内存段,基于 邮政。您可能需要使用信号量 以确保共享内存 操作是原子的。

    关于分叉和共享内存的教程在dev shed上:

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

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

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

        2
  •  4
  •   michalburger1    16 年前

    如果需要共享内存,那么使用线程而不是进程可能是更好的解决方案?

        3
  •  2
  •   Patrick Schlüter    15 年前

    我最近使用的共享内存变体是在分叉之前打开一个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;
    
    推荐文章