C:POSIX名称信号量无法共享累加流程
我遇到了一个在两个过程中创建名称名称器的问题。这是标题文件的相关内容,在两个程序中都调用(semctrl.h)
:
int init_sems()
{
char names[8][5] = {"sem1", "sem2", "sem3", "sem4", "sem5", "sem6", "sem7", "sem8"};
int failed = 1;
for (int i = 0; i < 8; i++)
{
sem[i] = sem_open(names[i], O_CREAT,00777, i>3);
failed = failed || (sem[i] == SEM_FAILED);
}
return failed;
}
sem
是信号量的全局数组,但我怀疑这是相关的。
两个程序都成功地调用此功能,但是当我打印信号量的地址时,我会为每个程序获得不同的值。这意味着他们都创建了一组8个不同的信号量,因此,它们无法正确同步。
我想念什么?
I'm having an issue creating named semaphores inside two processes. This is the relevant content for the header file that is being called inside both programs (semctrl.h)
:
int init_sems()
{
char names[8][5] = {"sem1", "sem2", "sem3", "sem4", "sem5", "sem6", "sem7", "sem8"};
int failed = 1;
for (int i = 0; i < 8; i++)
{
sem[i] = sem_open(names[i], O_CREAT,00777, i>3);
failed = failed || (sem[i] == SEM_FAILED);
}
return failed;
}
sem
is a global array of semaphores but I doubt this is relevant.
Both programs call this function successfully but when I print the addresses for the semaphores, I get different values for each program. This means they both create a set of 8 different semaphores, therefore, they can't sync properly.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Linux上:
命名的信号量是虚拟目录中的文件名:/dev/shm
名为信号量的个人具有格式:sem.name,name ins sem_open()function
使用信号量函数的名称,必须包括
pthread
参数时始终从信号量函数中检查返回的值。返回的值为0表示成功。如果返回-1,请检查errno是否发生故障原因。
请注意,当应用程序退出时,命名的信号量文件不会“走开”,而是需要调用
sem_unlink()
。请注意,如果通过sem_unlink()未链接命名的信号量文件,那么当该程序再次运行时,它仍将处于活动状态,并且先前运行中的信号量中留下的值仍将存在。
必须设置“访问位”,以便所有想要访问信号的程序都可以这样做。
On Linux:
A named semaphore is a file name in the virtual directory: /dev/shm
The individual named semaphores have the format: sem.name where name is from the sem_open() function
To use the semaphore functions must include the
pthread
parameter when linkingAlways check the returned value from the semaphore functions. A returned value of 0 indicates success. If a -1 is returned, then check errno for the cause of the failure.
Note that named semaphore files do not 'go away' when the application exits, but rather a call to
sem_unlink()
is needed.Note that if the named semaphore file is not unlinked via sem_unlink(), then it will still be active when that program is again run and the value left in the semaphore from the prior run will still be there.
The 'access bits' must be set so all the programs that want to access the semaphore can do so.