两次断开:你将如何处理这种情况

时间:2013-09-30 07:30:03

标签: c++

我有代码检查是否插入或删除了智能卡:

void checkCard(void *p)
{
//...
while(true)
{
    if (ReaderState1.dwEventState & SCARD_STATE_EMPTY)
    {
     // Smart card removed, call disconnect
     disconnectCard(cardHandle);

    }
    else
    {
     // Smart card inserted do smth else
    }


}

}

main中我调用上面的帖子:

int main()
{
...
    if(establichContext(_hSC) == true)
        {

            // Start thread 
            _beginthread(checkCard, 0, NULL);

            // Sleep
            Sleep(1000000); // or some other logic which halts program for some time

            // Disconnect from card and release context
            disconnectCard(cardHandle);
            releaseContext(_hSC);

        }
}

我的问题是,如果智能卡已被删除 - 通过第一个代码段(checkCard函数),调用disconnectCard - 第二次如main,则失败。你会如何处理这种情况?

disconnectCard - 只在内部使用SCardDisconnect方法)http://msdn.microsoft.com/en-us/library/windows/desktop/aa379475(v=vs.85).aspx

2 个答案:

答案 0 :(得分:0)

我只会处理与checkCard线程的断开连接。您可以通过使用标志来控制工作线程中的while循环,然后从main清除此标志以在您想要停止检查卡时停止该线程。然后,您可以在关闭线程时断开卡的连接。

例如:

#include <windows.h>
#include <process.h>
#include <iostream>

void checkCard(void *p)
{
    bool &keepgoing = *((bool *) p);
    while (keepgoing)
    {
        // do what you want with check card
        std::cout << "checking card" << std::endl;
        Sleep(2000);
    }
    // if card still connected disconnect
    std::cout << "cleanly exited" << std::endl;
}

int main(void)
{
    bool run = true;
    _beginthread(checkCard, 0, &run);

    Sleep(15000);

    // clear this flag to tell the worker thread to stop
    run = false;
    // wait for worker thread to finish - could have worker set flag
    // again so you can test it has finished card disconnect etc.
    Sleep(2000);
    // done.
    std::cout << "finished" << std::endl;
    return 0;
}

这是你正在寻找的行为吗?

答案 1 :(得分:-2)

有一个标记,您可以在disconnectCard函数中检查并设置。

void disconnectCard(someType someArgument)
{
    static bool disconnected = false;

    if (disconnected)
        return;  // Already disconnected

    // ... Do stuff ...

    disconnected = true;
}