0

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

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- 第二次如 in main,失败。你会如何处理这种情况?

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

4

2 回答 2

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;
}

那是您要寻找的行为吗?

于 2013-09-30T10:51:45.383 回答
-2

disconnectCard在函数中检查并设置一个标志。

喜欢

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

    if (disconnected)
        return;  // Already disconnected

    // ... Do stuff ...

    disconnected = true;
}
于 2013-09-30T07:35:25.530 回答