SUA + Visual Studio + pthreads - windows

I cannot compile this code under SUA:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * thread_function(void *arg) {
printf("thread_function started. Arg was %s\n", (char *)arg);
// pause for 3 seconds
sleep(3);
// exit and return a message to another thread
// that may be waiting for us to finish
pthread_exit ("thread one all done");
}
int main() {
int res;
pthread_t a_thread;
void *thread_result;
// create a thread that starts to run ‘thread_function’
pthread_create (&a_thread, NULL,
thread_function, (void*)"thread one");
printf("Waiting for thread to finish...\n");
// now wait for new thread to finish
// and get any returned message in ‘thread_result’
pthread_join(a_thread, &thread_result);
printf("Thread joined, it returned %s\n", (char *)thread_result);
exit(0);
}
I'm running on Windows 7 Ultimate x64 with Visual Studio 2008 and 2010 and I have installed:
Windows Subsystem for UNIX
Utilities and SDK for Subsystem for UNIX-based Applications in Microsoft Windows 7 and Windows Server 2008 R2
Include directories property of Visual Studio project is set to "C:\Windows\SUA\usr\include"
What I have to configure in order to compile and run (and possibly debug) pthreads programs in Visual Studio 2010 (or 2008)?

Related

keyboard interrupt routine visual studio C++ console app

I am using VS 2022 Preview to write a C++ console application. I wish to detect a keyboard hit and have my interrupt handler function called. I want the key press detected quickly in case main is in a long loop and therefore not using kbhit().
I found signal() but the debugger stops when the Control-C is detected. Maybe it is a peculiarity of the IDE. Is there a function or system call that I should use?
Edit: I am vaguely aware of threads. Could I spawn a thread that just watches kbd and then have it raise(?) an interrupt when a key is pressed?
I was able to do it by adding a thread. On the target I will have real interrupts to trigger my ISR but this is close enough for algorithm development. It seemed that terminating the thread was more trouble than it was worth so I rationalized that I am simulating an embedded system that does not need fancy shutdowns.
I decided to just accept one character at a time in the phony ISR then I can buffer them and wait and process the whole string when I see a CR, a simple minded command line processor.
// Scheduler.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <iostream>
#include <thread>
#include <conio.h>
void phonyISR(int tbd)
{
char c;
while (1)
{
std::cout << "\nphonyISR() waiting for kbd input:";
c = _getch();
std::cout << "\nGot >" << c << "<";
}
}
int main(int argc, char* argv[])
{
int tbd;
std::thread t = std::thread(phonyISR, tbd);
// Main thread doing its stuff
int i = 0;
while (1)
{
Sleep(2000);
std::cout << "\nMain: " << i++;
}
return 0;
}

C++ Segmentation Fault while using online Compiler but the Same works in VS Code

I am new to C++ Programming. I'm getting Segmentation Fault error while compiling my code in online compilers but when I try compile it using Visual Studio Code and g++ in offline(means in my local machine) works fine.
The Code I have tried is
`
#include <iostream>
int main() {
int *ptr;
*ptr = 10;
cout<<*ptr; //Prints 10
cout<<ptr; //Prints Some garbage address
}
But the above program not working in online compilers(used onlinegdb).
My machine configuration
g++ 11
Visual Studio Code 2016
This line *ptr = 10; is fundamentally wrong, as you cannot assign value by dereferencing a pointer.
The correct method of doing so, would be:
#include <iostream>
using namespace std;
int a=10;
int *ptr;
ptr=&a;
cout<<ptr<<endl;
cout<<*ptr<<endl;

How to name a thread in Windows Performance Analyzer?

I was trying to display the names of threads in Windows Performance Analyzer (WPA) (under Windows 8.1). This tool has a column called "thread name".
I followed the famous MSDN article:
http://msdn.microsoft.com/en-us/library/xcb2z8hs(v=vs.110).aspx
However, looks like it doesn't work in WPA. And according to a 3rd-party document, only Microsoft’s Visual Studio and WinDbg debuggers support this exception.
So how can I name a thread so that its name can be displayed in WPA?
Starting in Windows 10, version 1607, you can use the SetThreadDescription() API, which is now supported in xperf/WPA:
https://randomascii.wordpress.com/2015/10/26/thread-naming-in-windows-time-for-something-better/
You can also vote for support for it to be added to other Microsoft tools here:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/17608120-properly-support-native-thread-naming-via-the-sett
Dont have wpa installed handy so cant answer your query but thanks for
the question it never occurred to me that this could be used native code too
could come in handy
#include <windows.h>
#include <stdio.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
//EmptyBlock,Constant in__except() and lpparam not used in ThreadProc
#pragma warning( disable : 6312 6322 4100 )
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
DWORD WINAPI ThreadProc( LPVOID lpParam ) {
int ch = 0; while(ch != 'y') { ch = getchar(); } return 0;}
void SetThreadName( DWORD dwThreadID, char* threadName) {
THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName;
info.dwThreadID = dwThreadID; info.dwFlags = 0;
__try {
RaiseException( MS_VC_EXCEPTION, 0,
sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except( EXCEPTION_CONTINUE_EXECUTION) { }
}
void main (void) {
HANDLE hThread = NULL;
printf("\n\n\n=======Creating Thread And Naming It================\n\n\n");
if (( hThread = CreateThread(NULL,NULL,ThreadProc,NULL,NULL,NULL)) != NULL) {
SetThreadName(GetCurrentThreadId(), "\n\nMy New Shiny Thread\n\n");
WaitForSingleObject(hThread,INFINITE);
printf("Named Thread Terminated Main is terminating\n");
CloseHandle(hThread);
}
}
compiled linked and windbagged vcpp event seems to handle this exception in windbg
wonder what MAGIC Dword dbce handles
dir /b
compile.bat
threadname.cpp
type compile.bat
#call "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
cl /Zi /nologo /W4 /analyze *.cpp /link /RELEASE
compile.bat
Setting environment for using Microsoft Visual Studio 2010 x86 tools.
threadname.cpp
dir /b *.exe
threadname.exe
cdb -c "sxe -c \"~*;gc;\" vcpp;g;q" threadname.exe
0:000> cdb: Reading initial command 'sxe -c "~*;gc;" vcpp;g;q'
=================Creating Thread And Naming It===================
(f84.db4): Visual C++ exception - code 406d1388 (first chance)
. 0 Id: f84.db4 Suspend: 1 Teb: 7ffdf000 Unfrozen "
My New Shiny Thread
"
Start: threadname!mainCRTStartup (00401642)
Priority: 0 Priority class: 32 Affinity: 1
y
Named Thread Terminated Main is terminating
quit:

Best way to have crash dumps generated when processes crash?

In Windows environments (XP and Win 7):
What is the best way to automatically have a crash dump generated when processes crash on the system?
Can an installer (MSI) package do this?
One of the best way to have an automatic dump for any/specific process on Windows is to configure a set of entries in the registry. I tried the below on Windows 7 64 bit.
Open notepad.exe, paste the below entry and save it as "EnableDump.reg". You can give any name you wish.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps]
"DumpFolder"=hex(2):44,00,3a,00,5c,00,64,00,75,00,6d,00,70,00,00,00
"DumpCount"=dword:00000010
"DumpType"=dword:00000002
"CustomDumpFlags"=dword:00000000
Double click the "EnableDump.reg" and select 'Yes'. I have given the dump folder as 'd:\dump'. You can change it to whatever folder you wish.
Try to execute a crashing application, Windows will display the error dialog. Choose 'Close the Program' option. After that you will see the dump in the configured folder. The name of the dump file will be .exe..dmp.
For more details, you can refer the below link.
http://msdn.microsoft.com/en-us/library/bb787181(VS.85).aspx
Below explanation is based on another answer, but the logic is mine (without attribution need, as said on my profile);
Having your own dump generation framework which automatically creates a process dump when any Unhandled exception is encountered, would avoid clients having to install WinDbg.
At the application start up use SetUnhandledExceptionFilter(...) Win32 API to register a callback (i.e. application level exception-handler).
Now the registered callback function is called whenever there is any exception which is not handled. You may then create the process dump using MiniDumpWriteDump(...) API from DbgHelp.dll.
C++ Sample (unicode-enabled)
header-file
#ifndef CRASH_REPORTER_H
#define CRASH_REPORTER_H
//Exclude rarely used content from the Windows headers.
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# undef WIN32_LEAN_AND_MEAN
#else
# include <windows.h>
#endif
#include <tchar.h>
#include <DbgHelp.h>
class CrashReporter {
public:
inline CrashReporter() { Register(); }
inline ~CrashReporter() { Unregister(); }
inline static void Register() {
if(m_lastExceptionFilter != NULL) {
fprintf(stdout, "CrashReporter: is already registered\n");
fflush(stdout);
}
SetErrorMode(SEM_FAILCRITICALERRORS);
//ensures UnHandledExceptionFilter is called before App dies.
m_lastExceptionFilter = SetUnhandledExceptionFilter(UnHandledExceptionFilter);
}
inline static void Unregister() {
SetUnhandledExceptionFilter(m_lastExceptionFilter);
}
private:
static LPTOP_LEVEL_EXCEPTION_FILTER m_lastExceptionFilter;
static LONG WINAPI UnHandledExceptionFilter(_EXCEPTION_POINTERS *);
};
#endif // CRASH_REPORTER_H
source-file
#include "crash-report.h"
#include <stdio.h>
LPTOP_LEVEL_EXCEPTION_FILTER CrashReporter::m_lastExceptionFilter = NULL;
typedef BOOL (WINAPI *MiniDumpWriteDumpFunc)(HANDLE hProcess, DWORD ProcessId
, HANDLE hFile
, MINIDUMP_TYPE DumpType
, const MINIDUMP_EXCEPTION_INFORMATION *ExceptionInfo
, const MINIDUMP_USER_STREAM_INFORMATION *UserStreamInfo
, const MINIDUMP_CALLBACK_INFORMATION *Callback
);
LONG WINAPI CrashReporter::UnHandledExceptionFilter(struct _EXCEPTION_POINTERS *exceptionPtr)
{
//we load DbgHelp.dll dynamically, to support Windows 2000
HMODULE hModule = ::LoadLibraryA("DbgHelp.dll");
if (hModule) {
MiniDumpWriteDumpFunc dumpFunc = reinterpret_cast<MiniDumpWriteDumpFunc>(
::GetProcAddress(hModule, "MiniDumpWriteDump")
);
if (dumpFunc) {
//fetch system time for dump-file name
SYSTEMTIME SystemTime;
::GetLocalTime(&SystemTime);
//choose proper path for dump-file
wchar_t dumpFilePath[MAX_PATH] = {0};
_snwprintf_s(dumpFilePath, MAX_PATH, L"crash_%04d-%d-%02d_%d-%02d-%02d.dmp"
, SystemTime.wYear, SystemTime.wMonth, SystemTime.wDay
, SystemTime.wHour, SystemTime.wMinute, SystemTime.wSecond
);
//create and open the dump-file
HANDLE hFile = ::CreateFileW( dumpFilePath, GENERIC_WRITE
, FILE_SHARE_WRITE
, NULL
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_HIDDEN
, NULL
);
if (hFile != INVALID_HANDLE_VALUE) {
_MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;
exceptionInfo.ThreadId = GetCurrentThreadId();
exceptionInfo.ExceptionPointers = exceptionPtr;
exceptionInfo.ClientPointers = NULL;
//at last write crash-dump to file
bool ok = dumpFunc(::GetCurrentProcess(), ::GetCurrentProcessId()
, hFile, MiniDumpNormal
, &exceptionInfo, NULL, NULL
);
//dump-data is written, and we can close the file
CloseHandle(hFile);
if (ok) {
//Return from UnhandledExceptionFilter and execute the associated exception handler.
// This usually results in process termination.
return EXCEPTION_EXECUTE_HANDLER;
}
}
}
}
//Proceed with normal execution of UnhandledExceptionFilter.
// That means obeying the SetErrorMode flags,
// or invoking the Application Error pop-up message box.
return EXCEPTION_CONTINUE_SEARCH;
}
usage
#include "3rdParty/crash-report.h"
int main(int argc, char *argv[])
{
CrashReporter crashReporter;
(void)crashReporter; //prevents unused warnings
// [application main loop should be here]
return 0;
}
Windows XP:
The following steps enable automatic crash dumps:
1) Open a command prompt, running as administrator
2) Run drwtsn32 -i. This will install Doctor Watson as the default debugger when something crashes
3) Click Ok
4) From the command prompt, run drwtsn32
5) Set the Crash Dump path to your favorite directory, or leave the default.
6) Set the Crash Dump Type to mini. Note that under some circumstances, we may ask you for a full crash dump.
7) Make sure the Dump All Thread Contexts and Create Crash Dump File options are selected.
8) Click Ok
9) If a user.dmp file already exists in the Crash Dump path, delete it.
Windows 7: Location is:
C:\Users[Current User when app crashed]\AppData\Local\Microsoft\Windows\WER\ReportArchive

c/c++: thread to decrement a variable every 1 second? (in windows)

Well, I was planning to do this:
int seconds = 90;
void *DecreaseSeconds(){
while (seconds>-1)
{
seconds--;
sleep(1000);
}
return NULL;
}
int main(int argc, char *argv[]){
int threadid= pthread_create(&threads[i], NULL, DecreaseSeconds, NULL);
pthread_join(threadid, NULL);
}
Yet I get this dreadful thing when I try to compile on Visual Studio 2008
fatal error C1083: Cannot open include file: 'pthread.h': No such file or directory
I want a way to translate this to windows or make Visual Studio accept my posix thread.
Look up RTL function _beginthreadex.
There is no POSIX thread support on Win32. You need to use Win32 threads or an abstraction that supports both.

Resources