Linux上如何通过静态库同步进程?
我有一个家庭作业项目,需要创建一个静态库来提供对几个命名管道的相互访问。
这些管道用于使用库和服务器的各种客户端之间的通信。
现在,假设我想使用 pthread 互斥体;我怎样才能做到这一点?进程如何知道哪个是存储互斥锁的共享内存区域?谁应该需要这个内存区域?服务器不能,因为它需要库本身提供互斥。
感谢asveikau,我想出了这个:
#define SHARED 1
#define MUTEX 1
int main() {
sem_t* mutex = sem_open("mutex", O_CREAT);
sem_init(mutex, SHARED, MUTEX);
fork(), fork(), fork();
sem_wait(mutex);
int i;
for(i = 0; i < 10; i++)
printf("process %d %d\n", getpid(), i), fflush(stdout);
sem_post(mutex);
}
从输出看来确实解决了我的问题。
谢谢大家。
I have a homework project that require the creation of a STATIC library to provide mutual access to a couple of named pipes.
These pipes are used for communication between various clients using the library and a server.
Now, suppose I want to use pthread mutexes; how can I achieve that? How can the processes know which is the shared memory area in which the mutex is stored? And who should require this memory area? The server can't because it's required the library itself to provide mutual exclusion.
Thanks to asveikau i came up with this:
#define SHARED 1
#define MUTEX 1
int main() {
sem_t* mutex = sem_open("mutex", O_CREAT);
sem_init(mutex, SHARED, MUTEX);
fork(), fork(), fork();
sem_wait(mutex);
int i;
for(i = 0; i < 10; i++)
printf("process %d %d\n", getpid(), i), fflush(stdout);
sem_post(mutex);
}
that from the output really seem to solve my problem.
Thank you to everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我把这个写下来作为评论,但我认为这是值得回答的。
正如其他人所说,pthread 互斥体不是跨进程的。您需要的是“命名互斥体”。您可以使用
sem_open
创建跨进程信号量,并将其初始计数设置为 1。在这种情况下,sem_wait
变为“互斥锁”,sem_post
变为“互斥锁解锁”。请注意,
sem_open
虽然是 POSIX 的一部分,但并未得到普遍支持。我相信它可以在 Linux 和 Mac OS X 上运行。如果您关心的话,可能可以在 Solaris 上运行(现在您可能不关心)。我知道在 OpenBSD 上它总是会因ENOSYS
失败。 YMMV。I put this down as a comment, but it's worth an answer I think.
As others state, pthread mutexes are not cross-process. What you need is a "named mutex". You can use
sem_open
to create a cross-process semaphore, and give it an initial count of 1. In that casesem_wait
becomes "mutex lock" andsem_post
becomes "mutex unlock".Note that
sem_open
, while part of POSIX, is not universally supported. I believe it works on Linux and Mac OS X. Probably Solaris if you care about that (these days you probably don't). I know on OpenBSD it always fails withENOSYS
. YMMV.