【发布时间】:2012-07-29 19:34:24
【问题描述】:
在尝试解决一些调试问题时,我在代码中添加了一些printf-s:
我使用了那个代码:
struct PipeShm
{
int init;
sem_t sema;
...
...
}
struct PipeShm * sharedPipe = NULL;
函数2:
int func2()
{
if (!sharedPipe)
{
int myFd = shm_open ("/myregion", O_CREAT | O_TRUNC | O_RDWR, 0666);
if (myFd == -1)
error_out ("shm_open");
// allocate some memory in the region in the size of the struct
int retAlloc = ftruncate (myFd, sizeof * sharedPipe);
if (retAlloc < 0) // check if allocation failed
error_out("ftruncate");
// map the region and shared in with all the processes
sharedPipe = mmap (NULL, sizeof * sharedPipe,PROT_READ | PROT_WRITE,MAP_SHARED , myFd, 0);
if (sharedPipe == MAP_FAILED) // check if the allocation failed
error_out("mmap");
// put initial value
int value = -10;
// get the value of the semaphore
sem_getvalue(&sharedPipe->semaphore, &value);
if (sharedPipe->init != TRUE) // get in here only if init is NOT TRUE !
{
if (!sem_init (&sharedPipe->semaphore, 1, 1)) // initialize the semaphore to 0
{
sharedPipe->init = TRUE;
sharedPipe->flag = FALSE;
sharedPipe->ptr1 = NULL;
sharedPipe->ptr2 = NULL;
sharedPipe->status1 = -10;
sharedPipe->status2 = -10;
sharedPipe->semaphoreFlag = FALSE;
sharedPipe->currentPipeIndex = 0;
printf("\nI'm inside the critical section! my init is: %d\n" , sharedPipe->init);
}
else
perror ("shm_pipe_init");
printf("\nI'm out the critical section! my init is: %d\n" , sharedPipe->init);
}
}
return 1; // always successful
}
用那个主要的:
int main()
{
int spd, pid, rb;
char buff[4096];
fork();
func2();
return 0;
}
得到了这个:
shm_pipe_mkfifo:文件存在
I'm inside the critical section! my init is: 1
I'm out the critical section! my init is: 1
Output:hello world!
I'm inside the critical section! my init is: 1
I'm out the critical section! my init is: 1
好像共享内存不是这么共享的,为什么?
由于
MAP_SHARED | MAP_ANONYMOUS,该段在所有进程之间共享,那么为什么两个进程具有相同的before和after值?似乎每个进程都有自己的信号量,即使它是在它们之间共享的,那么出了什么问题?
谢谢
【问题讨论】:
-
已经在另一个问题中向您展示了如何正确使用信号量;你为什么坚持不这样做?
-
@KarolyHorvath:已更新,请看文末。
-
@ron,考虑到你从 SO 上的人那里获得的关于这个单一项目的大量帮助,当你提交完成的项目时,你真的应该指出 SO 作为你的代码的共同作者 :)
-
@HristoIliev:保留所有权利...
-
@HristoIliev:顺便说一句,我的朋友,我从不要求任何人为我解决我的硬件问题。我总是问一个问题,我在哪里展示我的代码,以及到目前为止我做了什么。
标签: c linux operating-system fork shared-memory