1
votes

I did below program, but it failed to delete the named_mutex in the end, print out result of "Mutex delete failure"

void IPC::testNamedMutex()
{
named_mutex mutex(open_or_create, "MyMutex");
for (int i = 0; i < 10; i++)
{
    mutex.lock();
    cout << "Mutex taken" << endl;

    std::fstream fs("test.txt", std::fstream::out | std::fstream::app);
    if (fs)
    {
        fs << "Thread id: " << boost::this_thread::get_id() << ", "
                << "Iteration " << i << endl;
    }

    boost::this_thread::sleep(boost::posix_time::seconds(1));
    mutex.unlock();
    cout << "Mutex is unlocked" << endl;

}
cout << "Delete the file and mutex?(y/n): ";
char c;
cin >> c;
if (c == 'y' || c == 'Y')
{
    if (remove("test.txt"))
        cout << "File deleted" << endl;
    else
        cout << "File delete failed" << endl;

    bool success=named_mutex::remove("MyMutex");
    if (success)
        cout << "Mutex removed" << endl;
    else
        cout << "Mutex delete failure" << endl;
}
}

However, if I run the remove with a second program such as below, it works. What could be the reason?

void IPC::testDeleteNamedMutex()
{
cout << named_mutex::remove("MyMutex") << endl;
}
1

1 Answers

0
votes

AFAIK This happens on windows if the mutex has been created while running in elevated context, but you try to remove it as a regular user.

In other words, UAC spoiling things again.

Theoretically, you should be able to set ACL (access control lists) to grant permissions to the intended users/groups. I haven't tried this. I'd consult Technet and/or your local administrators to find out more if you need to.