C语言中的fork()函数和共享内存

13

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

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

我快速地谷歌了一下,发现了IPC和各种技术,但我不知道哪种技术最适合我的情况。

那么,哪种技术最好?你能提供一个新手教程的链接吗?

谢谢。

3个回答

16

由于您提到要使用fork(),我认为您正在使用*nix系统

来自Unix.com

在UNIX IPCs中共享数据的主要方法是:

(1) 共享内存;

(2) 套接字:

还有其他UNIX IPCs,包括

(3) 消息队列。

(4) 信号量;

(5) 信号。

根据您的发帖情况,IPC的最佳选择是使用共享内存段。 您可能需要使用信号量来确保共享内存操作是原子的。

关于fork和共享内存的教程在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/


最终选择了共享内存。 - Cheetah
2
可疑的相似文本在这里(您可能需要链接以获得信用?):http://www.unix.com/programming/857-fork-ipc.html - sje397

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

这是一项大学作业。你必须特别使用fork()函数。 - Cheetah

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接