How to Explicitly Allocate memory to a Thread in C++ ? Am using Windows API for Multi-threading.While running sometimes it executes correctly but sometimes it shows "Heap Corruption","Unhandled Exception".Please guide me
This is the main() where i create the threads.
int main(int argc,char *argv[])
{
HANDLE hthread[MAX_THREADS];
//DWORD threadid;
FILETIME creation,exit,kernel,user;
SYSTEMTIME st1,st2;
//THREADENTRY32 entry;
char szEntrytime[255],szExittime[255];
directories.push_front(argv[1]);
files.clear();
Sem = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
if (Sem == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
return 1;
}
for(int i= 0;i<MAX_THREADS;i++)
{
hthread[i] = CreateThread(NULL,0,List,NULL,0,&threadid);
//hthread[i] = HeapAlloc(GetProcessHeap(),HEAP_NO_SERIALIZE,1024*30);
if( hthread[i] == NULL )
{
printf("CreateThread error: %d\n", GetLastError());
return 1;
}
}
Inside Thread
while(!directories.empty())
{
string path = directories.front();
string spec = path + "\\" + "*";
WaitForSingleObject(Sem,0L);
directories.pop_front();
ReleaseSemaphore(Sem,1,NULL);
HANDLE hfind = FindFirstFileA(spec.c_str(),&ffd);
if(hfind == INVALID_HANDLE_VALUE)
continue;
cout<< path <<endl;;
do
{
if(strcmp(ffd.cFileName,".") && strcmp(ffd.cFileName,".."))
{
if(ffd.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
{
WaitForSingleObject(Sem,0L);
directories.push_front(path + "\\" + ffd.cFileName);
ReleaseSemaphore(Sem,1,NULL);
}
else
{
files.push_back(path + "\\" + ffd.cFileName);
Files++;
}
}
}while(FindNextFileA(hfind,&ffd));
Use following logic for your threads (pseudo-code):
while ( true ) {
lock()
if ( empty ) {
unlock;
sleep;
continue;
} else {
get_one_dir;
remove_that_dir_from_list;
unlock;
}
process_the_dir;
continue;
}
For lock, use a Critical Section, and lock/unlock again when you want to push a new dir in the list.
Use same lock/unlock logic when reading/writing the files vector.
Use critical section for access shared resource:
EnterCriticalSection(&my_section);
//perform data manipulation per-thread
LeaveCriticalSection(&my_section);
Do not forget to initialize the critical section before using.
See this question to get help Problems using EnterCriticalSection
Related
i'm getting error:Debug Error R6010 -abort() has been called
in my code :
bool ListFiles(wstring path, wstring mask, vector<wstring>& files) {
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
wstring spec;
stack<wstring> directories;
directories.push(path);
files.clear();
while (!directories.empty()) {
path = directories.top();
spec = path + L"\\" + mask;
directories.pop();
hFind = FindFirstFile(spec.c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
return false;
}
do {
if (wcscmp(ffd.cFileName, L".") != 0 && wcscmp(ffd.cFileName, L"..") != 0) {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
directories.push(path + L"/" + ffd.cFileName);
}
else {
files.push_back(path + L"/" + ffd.cFileName);
}
}
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(hFind);
return false;
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
return true;}
void findText(std::string filename, std::string word , promise<string> &prom) {
std::ifstream f(filename);
std::string s;
std::string notFound = "no";
bool found = false;
if (!f) {
std::cout << "il file non esiste"<<std::endl;
}
while (f.good()) {
std::getline(f, s);
if (s.find(word, 0) != string::npos) {
found = true;
}
}
if (found) {
//cout << "Parola trovata in -> " << filename << endl;
prom.set_value_at_thread_exit(filename);
}
else {
prom.set_value_at_thread_exit(notFound);
}
f.close();}
int main(int argc, char* argv[]){
//vector<std::thread> th;
vector<future<string>> futures;
vector<wstring> files;
string search = "ciao";
string notFound = "no";
if (ListFiles(L"pds", L"*", files)) {
for (vector<wstring>::iterator it = files.begin(); it != files.end(); ++it) {
//wcout << it->c_str() << endl;
wstring ws(it->c_str());
string str(ws.begin(), ws.end());
// Show String
//cout << str << endl;
//Creo una promise per ogni thread in cui andrĂ² a cercare il risulato
std::promise<string> prom;
futures.push_back(prom.get_future());
std::thread(findText,str,search,std::ref(prom)).detach();
}
}
for (int i = 0; i < futures.size(); i++){
futures.at(i).wait();
if (futures.at(i).get().compare(notFound)!=0)
cout << "Parola trovata in ->" <<futures.at(i).get()<<endl;
}
return 0;}
I've tried before without using promises and making each thread printing the name of file if word was found and it worked.
So i don't know why using promises and future to retrive this value cause me this problem...
I'm using VS 2013
Lets take a close look at these lines lines:
for (...) {
...
std::promise<string> prom;
...
std::thread(findText,str,search,std::ref(prom)).detach();
}
First you create a local variable prom, and then you pass a reference to that variable to the thread.
The problem with this is that once the loop iterates, the variable prom goes out of scope and the object is destructed. The reference you once had no longer have anything it references. Using the reference will lead to undefined behavior.
So the solution is to not use references (or pointers to the prom variable), which leads to problems because std::promise can't be copied. It can, however, be moved:
std::thread(findText,str,search,std::move(prom)).detach();
Fir this you might need to make the thread function take the promise argument as a rvalue reference:
void findText(std::string filename, std::string word , promise<string> &&prom) {
...
}
If the above solution doesn't work, then you could use dynamic allocation using the new C++11 smart pointers like std::unique_ptr.
Then the thread function should take the smart pointer by value, like
void findText(std::string filename, std::string word , std::unique_ptr<std::promise<string>> prom) {
...
}
And you create the thread like
auto prom = std::make_unique<std::promise<std::string>>();
// Or if you don't have std::make_unique
// std::unique_ptr<std::promise<std::string>> prom(new std::promise<std::string>);
futures.push_back(prom->get_future();
std::thread(findText,str,search,std::move(prom)).detach();
Remember that in your thread function (findText) the variable prom is a pointer and you need to use the arrow operator when using it, like e.g.
prom->set_value_at_thread_exit(filename);
// ^^
// Note "arrow" operator here
I am implementing an XLSX spreadsheet Reader in Visual Studio C++ MFC app and am getting an access violation error when executing it multiple times:
First-chance exception at 0x7720e39e in VCT.exe: 0xC0000005: Access violation reading location 0x02bdddab.
Unhandled exception at 0x7720e39e in VCT.exe: 0xC0000005: Access violation reading location 0x02bdddab.
The program '[1756] VCT.exe: Native' has exited with code -1073741819 (0xc0000005).
The weird thing is that depending on the rest of my code, this can occur after the function being called twice, three times, or more... This makes me think that it has something to do with timing, but I only have the single thread running. Another one of my (more realistic) hypotheses is that it is an undefined behavior. This makes it especially difficult to debug. What confuses me is why this access violation would happen after multiple calls to the function.
Added to question:
I call the function getVectorAllIP every time a button is clicked. After a few clicks (calls to getVectorAllIP), the I get the access violation error on the first call to mm_XLSXReader.xlsxGetCellOffset.
vector<CString> CVCTDlg::getVectorAllIP(string ipName){
CString CSIP1;
vector<CString> VCSIPAddresses;
XLSXReader mm_XLSXReader;
mm_XLSXReader.reloadFile();
mm_XLSXReader.setFilePath(XLSX_FILE_PATH);
for(int i = 0; i < m_vectorStrHostname.size(); i++)
{
CSIP1="";
for(int iOffset = 0; iOffset < 4; iOffset++)
{
CSIP1.Append(mm_XLSXReader.xlsxGetCellOffset(ipName, i, iOffset).c_str());
if(iOffset != 3)
{
CSIP1.Append(".");
}
}
if(CSIP1 != "...")
{
VCSIPAddresses.push_back(CSIP1);
}else{
VCSIPAddresses.push_back("");
}
}
return VCSIPAddresses;
}
Within xlsxGetCellOffset, the access violation error occurs within readSheetXml.
string XLSXReader::xlsxGetCellOffset(string columnName, int id, int offset)
{
string contentToReturn;
id++;
if(!m_bFileInMemory)
{
if(openm_XLSXReader())
{
readSharedStringsXml();
readSheetXml();
closem_XLSXReaders();
m_bFileInMemory = true;
}
}
for(int i = 0; i < m_header.size(); i++)
{
if(m_header.at(i) == columnName && m_header.size() > i + offset)
{
if(m_sheetContent.size() > id)
{
if(m_sheetContent.at(id).size() > i)
{
contentToReturn = m_sheetContent.at(id).at(i+offset);
}
}
}
}
return contentToReturn;
}
The access violation occurs during the clearing sequence at the end. Specifically at the columnContent.clear(). If I remove columnContent.clear() it occurs at the next line tParameterColumn.clear().
void XLSXReader::readSheetXml()
{
if(m_m_XLSXReader)
{
int error = unzLocateFile(m_m_XLSXReader, SHEET_NAME, 0);
if(error == UNZ_OK)
{
error = unzOpenCurrentFile(m_m_XLSXReader);
if(error == UNZ_OK)
{
int readingStatus = 0;
char readBuffer[BUFFERSIZE];
string file;
int indexValue;
//Reading File
do
{
readingStatus = unzReadCurrentFile(m_m_XLSXReader, readBuffer, BUFFERSIZE);
file.append(readBuffer, readingStatus);
}while(readingStatus > 0);
//Sort Data
vector<string> rowContent;
rowContent = findXmlTagsContent(file, "row");
unsigned int iHdrSize;
m_header.clear();
vector<string> columnContent;
vector<string> tParameterColumn;
vector<string> rParameterColumn;
vector<string> tmpRow;
for(int i = 0 ; i < rowContent.size(); i++)
{
columnContent=findXmlTagsContent( rowContent.at(i), "c");
rParameterColumn=findXmlParameterInTag(rowContent.at(i), "c", "r");
tParameterColumn=findXmlParameterInTag(rowContent.at(i), "c", "t");
if(i==0){
iHdrSize = columnContent.size();
}
//Should be equal
if(columnContent.size() == tParameterColumn.size())
{
unsigned int iFilledColumns = 0;
for(int j = 0 ; j < columnContent.size(); j++)
{
int columnNumber = 0;
if(!rParameterColumn.at(j).empty())
{
columnNumber = columnLetter2Int(rParameterColumn.at(j));
}
vector<string> value;
value = findXmlTagsContent(columnContent.at(j), "v");
if(value.size()>1){
value.clear();
value.push_back("");
}
//Header Reading
if( i == 0)
{
//Fill empty spaces in excel sheet with ""
for(int a = 1; a < columnNumber-iFilledColumns; a++)
{
m_header.push_back("");
}
iFilledColumns=m_header.size();
//link to sharedString
if(tParameterColumn.at(j) == "s")
{
indexValue = atoi(value.at(0).c_str());
string tmpStr = m_sharedString.at(indexValue);
m_header.push_back(tmpStr);
}
//Value
else
{
m_header.push_back(value.at(0));
}
}
// Content Reading
else
{
////Fill empty spaces in excel sheet with ""
for(int a = 1; a < columnNumber-iFilledColumns; a++)
{
tmpRow.push_back("");
}
iFilledColumns=tmpRow.size();
//link to sharedString
if(tParameterColumn.at(j) == "s")
{
indexValue = atoi(value.at(0).c_str());
tmpRow.push_back(m_sharedString.at(indexValue));
}
//Value
else
{
if(value.size() != 0)
{
tmpRow.push_back(value.at(value.size()-1));
}
else
{
tmpRow.push_back("");
}
}
}
iFilledColumns++;
}
for(int k=0;k<iHdrSize-iFilledColumns;k++){
tmpRow.push_back("");
}
m_sheetContent.push_back(tmpRow);
tmpRow.clear();
columnContent.clear();
tParameterColumn.clear();
rParameterColumn.clear();
}
}
}
}
}
}
And just FYI, the m_m_XLSXReader is instantiated on a call to openm_XLSXReader called within xlsxGetCellOffset. Here it is for your reference:
bool XLSXReader::openm_XLSXReader()
{
//Uncompress .xlsx
m_m_XLSXReader = unzOpen(m_strXLSXPath.c_str());
if(m_m_XLSXReader){
return true;
}
return false;
}
Hope someone can point out some glaring obvious mistake, because I am starting to question my sanity :) Thanks.
This loop:
do
{
readingStatus = unzReadCurrentFile(m_m_XLSXReader, readBuffer, BUFFERSIZE);
file.append(readBuffer, readingStatus);
} while (readingStatus > 0);
will append the last read block twice, most likely producing invalid XML.
I don't know which library you use to read XML (can't find any references to findXmlTagsContent other than this question), and how resilient it is, but suspect it may not behave well being fed garbage. Plus, you are not checking for any possible errors...
Bottom line is: try reading your file like this:
while ((readingStatus = unzReadCurrentFile(m_m_XLSXReader, readBuffer, BUFFERSIZE)) > 0)
file.append(readBuffer, readingStatus);
Also, what are you going to do if the return is negative (an error code)?
OK, So thank you all for your help and suggestions.
Vlad, your suggestions really got me thinking in a more logical way and then I found the problem which was completely unrelated to the actual XLSX reading.
The simple explanation is that when I click the button that sets off the XLSX reader, I modify the windows registry before that. In the process of recursively removing some registry keys, some sort of memory corruption occurs, that was only reflected when I got the access violation. I fixed my registry code, and now the issue is has been resolved.
If anyone is interested about the actual issue regarding recursively deleting registry keys, keep reading...
I was using the code to recursively delete a registry key and its subkeys:
Deleting a Key with Subkeys
#include <windows.h>
#include <stdio.h>
#include <strsafe.h>
//*************************************************************
//
// RegDelnodeRecurse()
//
// Purpose: Deletes a registry key and all its subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
BOOL RegDelnodeRecurse (HKEY hKeyRoot, LPTSTR lpSubKey)
{
LPTSTR lpEnd;
LONG lResult;
DWORD dwSize;
TCHAR szName[MAX_PATH];
HKEY hKey;
FILETIME ftWrite;
// First, see if we can delete the key without having
// to recurse.
lResult = RegDeleteKey(hKeyRoot, lpSubKey);
if (lResult == ERROR_SUCCESS)
return TRUE;
lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);
if (lResult != ERROR_SUCCESS)
{
if (lResult == ERROR_FILE_NOT_FOUND) {
printf("Key not found.\n");
return TRUE;
}
else {
printf("Error opening key.\n");
return FALSE;
}
}
// Check for an ending slash and add one if it is missing.
lpEnd = lpSubKey + lstrlen(lpSubKey);
if (*(lpEnd - 1) != TEXT('\\'))
{
*lpEnd = TEXT('\\');
lpEnd++;
*lpEnd = TEXT('\0');
}
// Enumerate the keys
dwSize = MAX_PATH;
lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
if (lResult == ERROR_SUCCESS)
{
do {
StringCchCopy (lpEnd, MAX_PATH*2, szName);
if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) {
break;
}
dwSize = MAX_PATH;
lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
} while (lResult == ERROR_SUCCESS);
}
lpEnd--;
*lpEnd = TEXT('\0');
RegCloseKey (hKey);
// Try again to delete the key.
lResult = RegDeleteKey(hKeyRoot, lpSubKey);
if (lResult == ERROR_SUCCESS)
return TRUE;
return FALSE;
}
//*************************************************************
//
// RegDelnode()
//
// Purpose: Deletes a registry key and all its subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
BOOL RegDelnode (HKEY hKeyRoot, LPTSTR lpSubKey)
{
TCHAR szDelKey[MAX_PATH*2];
StringCchCopy (szDelKey, MAX_PATH*2, lpSubKey);
return RegDelnodeRecurse(hKeyRoot, szDelKey);
}
void __cdecl main()
{
BOOL bSuccess;
bSuccess = RegDelnode(HKEY_CURRENT_USER, TEXT("Software\\TestDir"));
if(bSuccess)
printf("Success!\n");
else printf("Failure.\n");
}
If I had values in the key I was trying to delete, then everything worked as expected. In the case where I had a key with a subkey inside of it, they were deleted, but I began have the issues of my question above.
So for example this was deleted without causing me a life of pain,
[KeyName1]
--> SOME_DWORD
--> SOME_STRING
And this one caused me much pain indeed,
[KeyName2]
--> SOME_DWORD
--> SOME_STRING
--> [SubKeyName]
-----> SOME_DWORD
-----> SOME_STRING
I'm writing a program that traces the execution of other programs. I'm using dynamic instruction instrumentation to track the behavior of x86's CMP instruction.
I'm using the windows debugging api to control the behavior of the debugged program. I start the program with the 'debug only this process' flag, and then set the trap flag on the main thread.
I then enter the main debugging loop:
bool cDebugger::ProcessNextDebugEvent(bool Verbose)
{
bool Result = true;
DEBUG_EVENT Event = { 0 };
DWORD Status = DBG_CONTINUE;
if (!WaitForDebugEvent(&Event, INFINITE))
{
_Reporter("Error: WaitForDebugEvent: " + to_string(GetLastError()));
return Result;
}
else
{
if (Event.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
{
if (Verbose)
_Reporter("Created process: " + GetFilenameFromHandle(Event.u.CreateProcessInfo.hFile));
}
else if (Event.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT)
{
if (Verbose)
_Reporter("Dll: " + GetFilenameFromHandle(Event.u.LoadDll.hFile) + " loaded at: " + to_string((unsigned int)Event.u.LoadDll.lpBaseOfDll));
_Dlls.insert(make_pair((unsigned int)Event.u.LoadDll.lpBaseOfDll, GetFilenameFromHandle(Event.u.LoadDll.hFile)));
}
else if (Event.dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT)
{
if (Verbose)
_Reporter("Thread[" + to_string(Event.dwThreadId) + "] created at: " + to_string((unsigned int)Event.u.CreateThread.lpStartAddress));
_Threads.push_back(Event.dwThreadId);
}
else if (Event.dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT)
{
if (Verbose)
_Reporter("Thread[" + to_string(Event.dwThreadId) + "] exited with: " + to_string(Event.u.ExitThread.dwExitCode));
auto It = std::find(_Threads.begin(), _Threads.end(), Event.dwThreadId);
if (It != _Threads.end())
_Threads.erase(It);
}
else if (Event.dwDebugEventCode == UNLOAD_DLL_DEBUG_EVENT)
{
if (Verbose)
_Reporter("Dll " + _Dlls[(unsigned int)Event.u.UnloadDll.lpBaseOfDll] + " unloaded at : " + to_string((unsigned int)Event.u.UnloadDll.lpBaseOfDll));
}
else if (Event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
{
if (Verbose)
_Reporter("Process exited with: " + to_string(Event.u.ExitProcess.dwExitCode));
Result = false;
_Threads.clear();
}
else if (Event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP)
{
Status = DBG_EXCEPTION_HANDLED;
}
else
{
Status = DBG_EXCEPTION_NOT_HANDLED;
}
}
for (size_t i = 0; i < _Threads.size(); i++)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, _Threads[i]);
if (hThread == NULL)
{
_Reporter("Error: Failed to open thread: " + to_string(GetLastError()));
}
else
{
CONTEXT ThreadContext = GetThreadContext(hThread);
ProcessStep(ThreadContext, hThread);
ThreadContext.EFlags |= 0x100; // Set trap flag.
SetThreadContext(hThread, ThreadContext);
CloseHandle(hThread);
}
}
if (!ContinueDebugEvent(Event.dwProcessId, Event.dwThreadId, Status))
{
_Reporter("Error: ContinueDebugEvent: " + to_string(GetLastError()));
}
}
return Result;
}
As you can see I loop through all threads at the end of the function to make sure that the single-step exception will trigger on every next instruction in every thread.
However sometimes execution seems to 'escape' this trap, often executing millions of instructions before being caught again by the next debugging event.
I wrote another small application to test the behavior of my program:
int main(int argc, char* argv[])
{
//__asm int 3h
if (argc == 41234123)
{
printf("Got one\n");
}
return 0;
}
The expected output of the tracer should be:
0xDEADBEEF CMP 1 41234123
However somehow the tracer does not record this instruction (indicating that no debug event was raised, and that the trap flag was not set).
Can anybody see if I'm doing something wrong in my debug loop? Or what kind of behavior of the test program (loading of a dll) could be responsible for this?
The problem had something to do with code entering kernel space when calling windows apis. My solution was to set the page protection of the executable section of the test program to PAGE_GUARD:
SYSTEM_INFO Info;
GetSystemInfo(&Info);
DWORD StartAddress = (DWORD)Info.lpMinimumApplicationAddress;
DWORD StopAddress = (DWORD)Info.lpMaximumApplicationAddress;
DWORD PageSize = 0;
PageSize = Info.dwPageSize;
_Sections.clear();
for (DWORD AddressPointer = StartAddress; AddressPointer < StopAddress; AddressPointer += PageSize)
{
MEMORY_BASIC_INFORMATION Buffer;
VirtualQueryEx(_Process.GetHandle(), (LPCVOID)AddressPointer, &Buffer, sizeof(Buffer));
if (CheckBit(Buffer.Protect, 4) || CheckBit(Buffer.Protect, 5) || CheckBit(Buffer.Protect, 6) || CheckBit(Buffer.Protect, 7))
{
if (Buffer.State == MEM_COMMIT)
{
_Sections.push_back(make_pair((unsigned int)Buffer.BaseAddress, (unsigned int)Buffer.RegionSize));
AddressPointer = (unsigned int)Buffer.BaseAddress + (unsigned int)Buffer.RegionSize;
}
}
}
void cDebugger::SetPageGuard()
{
for (size_t i = 0; i < _Sections.size(); i++)
{
DWORD Dummy;
VirtualProtectEx(_Process.GetHandle(), (LPVOID)_Sections[i].first, _Sections[i].second, PAGE_GUARD | PAGE_EXECUTE_READWRITE, &Dummy);
}
}
This way I regain control because the system will fire a EXCEPTION_GUARD_PAGE when execution returns to a guarded page.
if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP)
{
Status = DBG_CONTINUE;
if (!_Tracing)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, Event.dwThreadId);
CONTEXT ThreadContext = GetThreadContext(hThread);
if (ThreadContext.Eip == _EntryAddress)
{
ClearHardwareBreakpoint(0, hThread);
_Tracing = true;
}
CloseHandle(hThread);
}
SetPageGuard();
_Guarded = true;
}
else if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
{
Status = DBG_CONTINUE;
}
else if (Event.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_GUARD_PAGE)
{
Status = DBG_CONTINUE; // fires when processor lands on guarded pages
}
else
{
Status = DBG_EXCEPTION_NOT_HANDLED;
}
This solution is not perfect. There are possibly still some situations under which execution can still escape the 'trap'. But it solved my most immediate problem (being able to see the comparisons in my test program).
I want to make it so when a user attaches a - after a command it will be executed in the background. For some reason if I execute a command normally it will wait, then if I execute a command in the background it will work but then if I execute a command normally it won't wait for it. I am sure I am just doing something small-ish wrong. Any ideas:
void executeSystemCommand(char *strippedCommand, char *background, int argc, char **args) {
char pathToExecute[80];
// Check if command will be executed in the background
int shellArgs;
bool bg;
if (!strcmp(background, "-")) {
bg = true;
shellArgs = argc -1;
} else {
bg = false;
shellArgs = argc;
}
// Save the linux commands in a new array
char *executableCommands[shellArgs+1];
int j;
for (j = 0; j < shellArgs+1; j++) {
executableCommands[j] = args[j];
}
executableCommands[shellArgs] = NULL;
// Check the $PATH
const char delimiters[] = ":";
char *token, *cp;
char *forLater;
int count = 0;
char *path;
path = getenv("PATH");
// All of this just breaks up the path into separate strings
cp = strdup(path);
forLater = strdup(path);
token = strtok (cp, delimiters);
while ((token = strtok (NULL, delimiters)) != NULL) {
count++;
}
char **argv;
int size = count+1;
argv = (char**) malloc (size);
count = 0;
token = strtok (forLater, delimiters);
argv[0] = (char*) malloc (50);
argv[0] = token;
strcpy(argv[0],token);
while ((token = strtok (NULL, delimiters)) != NULL) {
count++;
argv[count] = (char*) malloc (50);
argv[count] = token;
}
// This goes through the path to see if the linux command they entered
// Ex: sleep exists in one of those files and saves it to a var
int i;
bool weHaveIt = false;
int ac;
for (i = 0; i < count; i++) {
char str[80];
strcpy(str, argv[i]);
strcat(str, "/");
strcat(str, args[0]);
ac = access(str, F_OK);
if (ac == 0) {
weHaveIt = true;
strcpy(pathToExecute, str);
break;
}
}
if (!weHaveIt) {
printf("That is not a valid command. SORRY!\n");
return;
}
executableCommands[0] = pathToExecute;
int status;
// Get the array for
// If user wants command to be a background process
if (bg) {
int background_process_id;
pid_t fork_return;
fork_return = fork();
if (fork_return == 0) {
background_process_id = getpid();
addJobToTable(strippedCommand, background_process_id);
setpgid(0, 0);
execve(executableCommands[0], executableCommands, NULL);
exit(0);
} else {
return;
}
} else {
int background_process_id;
pid_t fork_return;
fork_return = fork();
if (fork_return == 0) {
background_process_id = getpid();
status = execve(executableCommands[0], executableCommands, NULL);
exit(0);
} else {
wait(&status);
return;
}
}
}
The call to wait made for the third job returns immediately because the second job has finished and is waiting to be handled (also called "zombie"). You could check the return value of wait(&status), which is the PID of the process that has exited, and make sure it is the process you were waiting for. If it's not, just call wait again.
Alternatively use waitpid, which waits for a specific process:
/* Wait for child. was: wait(&status) */
waitpid(fork_return, &status, 0);
If you do this you should implement a signal handler for SIGCHLD to handle finished background jobs to prevent the accumulation of "zombie" child processes.
In addition to that, in the background job case, the branch where fork() returns 0 you are already in the new process, so the call to addJobToTable happens in the wrong process. Also, you should check the return values of all the calls; otherwise something may be failing and you don't know it. So the code for running a job in the background should look more like this:
if (fork_return == 0) {
setpgid(0, 0);
if (execve(executableCommands[0], executableCommands, NULL) == -1) {
perror("execve");
exit(1);
}
} else if (fork_return != -1) {
addJobToTable(strippedCommand, fork_return);
return;
} else {
perror("fork"); /* fork failed */
return;
}
Every child process created with fork() will exit when the parent process exits.
if (fork_return == 0) {
/* child process, do stuff */
} else {
/* parent process, exit immediately */
return;
}
Explanation
fork spawns a new process as a child process of the current process (parent). Whenever a process in Unix-like operating systems terminates all of its child processes are going to be terminated too. If they have child processes on their own, then these will get terminated too.
Solution
On most shells you can start a process in background if you add an ampersand & to the end of the line:
myApplication arg1 arg2 arg3 ... argN &
I'm trying to do some basic parallel processing to do an odd-even sort on integers using POSIX shared memory segments and unnamed semaphores. I have pretty much everything working at this point, except for one final thing: if I do not perror() directly after semaphore locks/unlocks the code acts differently (and subsequently sorts incorrectly). If I leave the perror() calls directly after semaphore locks and unlocks in, the code sorts the array of integers perfectly.
int semaphoreCheck = sem_init(&(sharedData->swapSem), 1, 1);
if (semaphoreCheck == -1)
{
perror( "failed to initialize semaphore" );
exit(EXIT_FAILURE);
}
pid_t fork1;
fork1 = fork();
if (fork1 == 0)
{
// original.child
pid_t fork2;
fork2 = fork();
if (fork2 == 0)
{
// child.child
// do a portion of the sort here
while(sharedData->evenSwap || sharedData->oddSwap)
{
// obtain lock on the shared vector
// int commandCheck = shmctl(sharedID, SHM_LOCK, NULL);
int commandCheck = sem_wait(&(sharedData->swapSem));
perror("semaphore lock");
// if lock was obtained
if (commandCheck == 0)
{
sharedData->evenSwap = false;
for( int index = 1; index < arraySize - 1; index +=2)
{
if( sharedData->vecData[index] > sharedData->vecData[index + 1] )
{
int temp;
temp = sharedData->vecData[index];
sharedData->vecData[index] = sharedData->vecData[index+1];
sharedData->vecData[index+1] = temp;
sharedData->evenSwap = true;
}
}
// release lock on the shared vector
commandCheck = sem_post(&(sharedData->swapSem));
perror("semaphore unlock");
if (commandCheck == -1)
{
perror("failed to unlock shared semaphore");
}
}
else perror("failed to lock shared semaphore");
}
_exit(0);
}
else if (fork2 > 0)
{
// child.parent
// do a portion of the sort here
while(sharedData->evenSwap || sharedData->oddSwap)
{
// obtain lock on the shared vector
int commandCheck = sem_wait(&(sharedData->swapSem));
perror("semaphore lock");
// if lock was obtained
if (commandCheck == 0)
{
sharedData->oddSwap = false;
for( int index = 0; index < arraySize - 1; index +=2)
{
if( sharedData->vecData[index] > sharedData->vecData[index + 1] )
{
int temp;
temp = sharedData->vecData[index];
sharedData->vecData[index] = sharedData->vecData[index+1];
sharedData->vecData[index+1] = temp;
sharedData->oddSwap = true;
}
}
// release lock on the shared vector
commandCheck = sem_post(&(sharedData->swapSem));
perror("semaphore unlock");
if (commandCheck == -1)
{
perror("failed to unlock shared semaphore");
}
}
else perror("failed to lock shared semaphore");
}
_exit(0);
}
else
{
// child.error
// forking error.
perror("failed to fork in child");
exit(EXIT_FAILURE);
}
}
else if( fork1 > 0)
{
// original.parent
// wait for the child process to finish.
waitpid(fork1, NULL, 0);
}
else
{
// forking error
perror("failed to fork");
exit(EXIT_FAILURE);
}
I can only guess that this has to do with how the semaphore blocks the process if a wait cannot be fulfilled, but I do not understand how perror() calls fix it.
I think your problem may be related to the way you are (not) checking that the conditions still apply after you get the semaphore, or that the checking conditions are themselves wrong.
You have:
while(sharedData->evenSwap || sharedData->oddSwap)
{
// obtain lock on the shared vector
int commandCheck = sem_wait(&(sharedData->swapSem));
perror("semaphore lock");
// if lock was obtained
if (commandCheck == 0)
{
sharedData->oddSwap = false;
After you get the semaphore, you should probably validate that either sharedData->evenSwap or sharedData->oddSwap is still true, relinquishing the semaphore if not. This is a standard idiom; you check, lock and recheck, because the status may have changed between the original check and the time you gain the lock.
Under this hypothesis, the perror() calls alter the timing of the processes, allowing the conditions to stay unchanged for longer than when the perror() calls are not present. So, there is a timing problem here, somewhere.