Reputation: 56509
I have a problem with semaphores in Windows between two application. An application waits for release signal(Qt) and the other application sends release signal(MSVC2008). But it dose not work.
I tested Qt-Qt and MSVC2008-MSVC2008 modes and they was succeed. But when I try Qt-MSVC2008 mode it fails.
// MSVC2008:
#include <windows.h>
#include <stdio.h>
int main()
{
const WCHAR semName[] = L"TestSem";
PHANDLE sem = (HANDLE *) CreateSemaphore (NULL, 0, 1, semName);
if (sem == NULL)
{
sem = (HANDLE *)OpenSemaphore (SEMAPHORE_ALL_ACCESS, 0, semName);
}
if (sem == NULL)
{
printf("OPEN/CREATE ERROR\n");
return 0;
}
BOOL r = ReleaseSemaphore(sem, 1 ,NULL);
if (r)
printf("OK\n");
else
printf("RELEASE ERROR\n");
CloseHandle (sem);
return 0;
}
and
// Qt 4.8.0 :
#include <QSystemSemaphore>
#include <QCoreApplication>
#include <iostream>
int main()
{
QSystemSemaphore *sem_read = new QSystemSemaphore("TestSem");
std::cout << "Wait for signal: " << std::endl;
while (1)
{
sem_read->acquire();
std::cout << "Hi" << std::endl;
}
return 0;
}
I expect when Qt-app is running, after executing MSVC2008-app, it prints one "Hi" in the screen. But it dose not. What is the problem?!
Note: I'm using Windows 7 and MinGW compiler for Qt
Upvotes: 2
Views: 2427
Reputation: 4276
Looking at the Qt sources (4.7.3) I see at corelib/kernel/qsystemsemaphore_p.h:79
that the semaphore name generated by Qt is prefixed by qipc_systemsem_
.
[UPDATE] The sha1 hash of "TestSem" is also appended, so the resulting Qt semaphore name is qipc_systemsem_TestSem3ec37c26f212774998f34a4e6722cac152ad17fa
Confirmed working.
To generate the semaphore name:
QString prefix = "qipc_systemsem_";
QString key = "TestSem";
QString result = prefix;
QString part1 = key;
part1.replace(QRegExp(QLatin1String("[^A-Za-z]")), QString());
result.append(part1);
QByteArray hex = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1).toHex();
result.append(QLatin1String(hex));
qDebug() << result;
Upvotes: 4
Reputation: 49255
2 things I'd look into:
QSystemSemaphore
requires an initial values and initiated with 0 if it is not given. Maybe start it with 1?
this is a system semaphore, could it be that your first test did not release it? try to change the name maybe.
Upvotes: 0