Biến thể mà tôi đã sử dụng gần đây của bộ nhớ dùng chung là mở mmap trước khi tắt. Điều này tránh những hạn chế nhất định của api bộ nhớ dùng chung. Bạn không có giới hạn kích thước (phạm vi địa chỉ là giới hạn), bạn không cần phải tạo khóa từ tệp tuyệt đối đó. Dưới đây là ví dụ về cách tôi đã thực hiện (Tôi đã bỏ sót lỗi kiểm tra vì lợi ích ngắn gọn)
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;
Nguồn
2011-06-10 16:22:02
Đã đến với bộ nhớ dùng chung ở cuối. – Cheetah
Văn bản tương tự đáng ngờ ở đây (bạn có thể muốn liên kết tín dụng?): Http://www.unix.com/programming/857-fork-ipc.html – sje397
@ sje397: Cảm ơn bạn đã chỉ ra cho tôi lỗi trích dẫn – sum1stolemyname