This question already has answers here:
How to check if a process is running or not using C++
(3 answers)
Closed 9 years ago.
Hi iuse this code for check Process after my App "piko.exe" run and if the programs such as
"non.exe","firefox.exe","lol.exe" if running closed my App and return an error.
But i need to this check process every 30 sec and i used while but my main program (this code is one part of my project) stopped working so pleas if possible pls someone edited my code thank you.
#include "StdInc.h"
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <stdio.h>
void find_Proc(){
HANDLE proc_Snap;
HANDLE proc_pik;
HANDLE proc_pikterm;
PROCESSENTRY32 pe32;
PROCESSENTRY32 pe32pik;
int i;
char* chos[3] = {"non.exe","firefox.exe","lol.exe"};
char* piko = "piko.exe";
proc_pik = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
proc_Snap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof(PROCESSENTRY32);
pe32pik.dwSize = sizeof(PROCESSENTRY32);
for(i = 0; i < 3 ; i++){
Process32First(proc_Snap , &pe32);
do{
if(!strcmp(chos[i],pe32.szExeFile)){
MessageBox(NULL,"CHEAT DETECTED","ERROR",NULL);
Process32First(proc_pik,&pe32pik);
do{
if(!strcmp(iw4m,pe32pik.szExeFile)){
proc_pikterm = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pe32pik.th32ProcessID);
if(proc_pikterm != NULL)
TerminateProcess(proc_pikterm, 0);
CloseHandle(proc_pikterm);
}
} while(Process32Next(proc_pik, &pe32pik));
}
} while(Process32Next(proc_Snap, &pe32));
}
CloseHandle(proc_Snap);
CloseHandle(proc_pik);
}
Based on what OS you're using you can poll the system time and check to see if 30 seconds have expired. The way to do so is to take the time at the beginning of your loop, take the time at the end and subtract them. Then subtract the time you want to sleep from the time it took your code to run that routine.
Also, if you don't need EXACTLY 30 seconds, you could just add sleep(30) to your loop.
Can you explain to me why this method wouldn't work for you? The code below is designed to count up one value each second. Make "checkMyProcess" do whatever you need it to do within that while loop before the sleep call.
#include <iostream>
using namespace std;
int someGlobal = 5;//Added in a global so you can see what fork does, with respect to not sharing memory!
bool checkMyProcess(const int MAX) {
int counter = 0;
while(counter < MAX) {
cout << "CHECKING: " << counter++ << " Global: " << someGlobal++ << endl;
sleep(1);
}
}
void doOtherWork(const int MIN) {
int counter = 100;
while(counter > MIN) {
cout << "OTHER WORK:" << counter-- << " Global: " << someGlobal << endl;
sleep(1);
}
}
int main() {
int pid = fork();
if(pid == 0) {
checkMyProcess(5);
} else {
doOtherWork(90);
}
}
Realize of course that, if you want to do work outside of the while loop, within this same program, you would have to use threading, or fork a pair of processes.
EDIT:
I added in a call to "fork" so you can see the two processes doing work at the same time. Note: if the "checkMyProcess" function needs to know something about the memory going on in the "doOtherWork" function threading will be a much easier solution for you!
Related
I have a console application that is intended to only run on windows. It is written in C++. Is there any way to wait 60 seconds (and show remaining time on screen) and then continue code flow?
I've tried different solutions from the internet, but none of them worked. Either they don't work, or they don't display the time correctly.
//Please note that this is Windows specific code
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
int counter = 60; //amount of seconds
Sleep(1000);
while (counter >= 1)
{
cout << "\rTime remaining: " << counter << flush;
Sleep(1000);
counter--;
}
}
You can use sleep() system call to sleep for 60 seconds.
You can follow this link for how to set 60 seconds timer using system call Timer in C++ using system calls.
possible use Waitable Timer Objects with perion set to 1 second for this task. possible implementation
VOID CALLBACK TimerAPCProc(
__in_opt LPVOID /*lpArgToCompletionRoutine*/,
__in DWORD /*dwTimerLowValue*/,
__in DWORD /*dwTimerHighValue*/
)
{
}
void CountDown(ULONG Seconds, COORD dwCursorPosition)
{
if (HANDLE hTimer = CreateWaitableTimer(0, 0, 0))
{
static LARGE_INTEGER DueTime = { (ULONG)-1, -1};//just now
ULONGLONG _t = GetTickCount64() + Seconds*1000, t;
if (SetWaitableTimer(hTimer, &DueTime, 1000, TimerAPCProc, 0, FALSE))
{
HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
do
{
SleepEx(INFINITE, TRUE);
t = GetTickCount64();
if (t >= _t)
{
break;
}
if (SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition))
{
WCHAR sz[8];
WriteConsoleW(hConsoleOutput,
sz, swprintf(sz, L"%02u..", (ULONG)((_t - t)/1000)), 0, 0);
}
} while (TRUE);
}
CloseHandle(hTimer);
}
}
COORD dwCursorPosition = { };
CountDown(60, dwCursorPosition);
this might be of some help, it's not entirely clear what the question is but this is a countdown timer from 10 seconds, you can change the seconds and add minutes as well as hours.
#include <iomanip>
#include <iostream>
using namespace std;
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
int main()
{
for (int sec = 10; sec < 11; sec--)
{
cout << setw(2) << sec;
cout.flush();
sleep(1);
cout << '\r';
if (sec == 0)
{
cout << "boom" << endl;
}
if (sec <1)
break;
}
}
In c++ you can use countdown. please go through with the following logic which will allow you to show remaining time on the screen.
for(int min=m;min>0;min--) //here m is the total minits as per ur requirements
{
for(int sec=59;sec>=;sec--)
{
sleep(1); // here you can assign any value in sleep according to your requirements.
cout<<"\r"<<min<<"\t"<<sec;
}
}
if you need more help on this then please follow the link here
Hope it will work, please let me know that it is working in your case or not? or if you need any help.
Thanks!
Hello I was trying to break the loop in middle of its execution.The loop shows a countdown of seconds from 5-1 .I want to break the loop in middle using any keystroke entered by the user.I researched for some time and created a thread. I set a global variable and updated it in the second thread. I gave a condition in the main function using that global variable but the loop doesn't break.
Here is the code.
Please help.
#include<iostream>
#include<windows.h>
#include<stdlib.h>
#include<iomanip>
#include<stdio.h>
using namespace std;
bool stop=false;
DWORD WINAPI thread1(LPVOID pm)
{
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
return 0;
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
system("PAUSE");
}
The program counts down and in middle of the count down i tried to break the loop.thread1 function takes an input and modifies stop(global variable). But the loop in main function doesn't break(it should).Loop goes on decreasing loop variable, becomes zero and loop ends.
You have to declare stop as volatile
volatile bool stop
It informs compiler not optimized (by cache) access to variable, because another thread can modify it.
Also, take care about read and write access on global variable by many thread : in most of case, you have to protect them using mutex. (I think in your case it's not necessary according basic small type and basic access, but take care)
EDIT
As ask in comments, this is my design when inverting thread :
#include<iostream>
#include<windows.h>
#include<stdlib.h>
#include<iomanip>
#include<stdio.h>
using namespace std;
volatile bool stop = false;
DWORD WINAPI thread1(LPVOID pm)
{
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
return 0;
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
WaitForSingleObject(handle, INFINITE);
system("PAUSE");
}
With this solution, it will stop after waiting 1s. If you want to terminate immediatly, you can use TerminateThread but read this before : https://msdn.microsoft.com/en-us/library/windows/desktop/ms686717%28v=vs.85%29.aspx
Found it. getchar() was waiting for carriage return. So i used _getch() from conio library. Like this.
#include<iostream>
#include<Windows.h>
#include<conio.h>
#include<stdlib.h>
#include<iomanip>
using namespace std;
volatile bool stop = false;
DWORD WINAPI thread1(LPVOID pm)
{
int a = 0;
while (a==0)
{
a = _getch();
}
stop = true;
return 0;
}
int main()
{
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
int i;
for ( i = 5; i > 0 && !stop; i--)
{
cout << "\n\n\n\n\n\n";
cout << setw(35);
cout << i;
Sleep(1000);
system("CLS");
}
if (i != 0)
cout << "Loop broken sucessflly.\n";
else
cout << "Attempt failed\n";
system("PAUSE");
}
I created a program that tests carchive. I wanted to see how fast it took to save a million data points:
#include "stdafx.h"
#include "TestData.h"
#include <iostream>
#include <vector>
using namespace std;
void pause() {
cin.clear();
cout << endl << "Press any key to continue...";
cin.ignore();
}
int _tmain(int argc, _TCHAR* argv[])
{
int numOfPoint = 1000000;
printf("Starting test...\n\n");
vector<TestData>* dataPoints = new vector<TestData>();
printf("Creating %i points...\n", numOfPoint);
for (int i = 0; i < numOfPoint; i++)
{
TestData* dataPoint = new TestData();
dataPoints->push_back(*dataPoint);
}
printf("Finished creating points.\n\n");
printf("Creating archive...\n");
CFile* pFile = new CFile();
CFileException e;
TCHAR* fileName = _T("foo.dat");
ASSERT(pFile != NULL);
if (!pFile->Open(fileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive, &e))
{
return -1;
}
bool bReading = false;
CArchive* pArchive = NULL;
try
{
pFile->SeekToBegin();
UINT uMode = (bReading ? CArchive::load : CArchive::store);
pArchive = new CArchive(pFile, uMode);
ASSERT(pArchive != NULL);
}
catch (CException* pException)
{
return -2;
}
printf("Finished creating archive.\n\n");
//SERIALIZING DATA
printf("Serializing data...\n");
for (int i = 0; i < dataPoints->size(); i++)
{
dataPoints->at(i).serialize(pArchive);
}
printf("Finished serializing data.\n\n");
printf("Cleaning up...\n");
pArchive->Close();
delete pArchive;
pFile->Close();
delete pFile;
printf("Finished cleaning up.\n\n");
printf("Test Complete.\n");
pause();
return 0;
}
When I run this code, it takes some time to create the data points, but then it runs through the rest of the code almost instantly. However, I then have to wait about 4 minutes for the application to actually finish running. I would assume the application would wait hang at the serializing data portion just like it did during the creation of the data points.
So my question is about how this actually work. Does carchive do its thing on a separate thread and allow the rest of the code to execute?
I can provide more information if necessary.
If you want to create a vector with a million elements that are all default-initialized you just just use this version of the constructor
vector<TestData> dataPoints{numOfPoint};
You should stop newing everything, let RAII handle the cleanup for you.
Also, know that push_back requires a resize of your vector if it's capacity isn't large enough, so if you start with an empty vector, and know how big it is going to be at the end, you can use reserve ahead of time.
vector<TestData> dataPoints;
dataPoints.reserve(numOfPoint);
for (int i = 0; i < numOfPoint; i++)
{
dataPoints->push_back(TestData{});
}
I have been dabbling with writing a C++ program that would control spark timing on a gas engine and have been running in to some trouble. My code is very simple. It starts by creating a second thread that works to emulate the output signal of a Hall Effect sensor that is triggered once per engine revolution. My main code processes the fake sensor output, recalculates engine rpm, and then determines the time necessary to wait for the crankshaft to rotate to the correct angle to send spark to the engine. The problem I'm running into is that I am using a sleep function in milliseconds and at higher RPM's I am losing a significant amount of data.
My question is how are real automotive ECU's programed to be able to control spark at high RPM's accurately?
My code is as follows:
#include <iostream>
#include <Windows.h>
#include <process.h>
#include <fstream>
#include "GetTimeMs64.cpp"
using namespace std;
void HEEmulator(void * );
int HE_Sensor1;
int *sensor;
HANDLE handles[1];
bool run;
bool *areRun;
int main( void )
{
int sentRpm = 4000;
areRun = &run;
sensor = &HE_Sensor1;
*sensor = 1;
run = TRUE;
int rpm, advance, dwell, oHE_Sensor1, spark;
oHE_Sensor1 = 1;
advance = 20;
uint64 rtime1, rtime2, intTime, curTime, sparkon, sparkoff;
handles[0] = (HANDLE)_beginthread(HEEmulator, 0, &sentRpm);
ofstream myfile;
myfile.open("output.out");
intTime = GetTimeMs64();
rtime1 = intTime;
rpm = 0;
spark = 0;
dwell = 10000;
sparkoff = 0;
while(run == TRUE)
{
rtime2 = GetTimeMs64();
curTime = rtime2-intTime;
myfile << "Current Time = " << curTime << " ";
myfile << "HE_Sensor1 = " << HE_Sensor1 << " ";
myfile << "RPM = " << rpm << " ";
myfile << "Spark = " << spark << " ";
if(oHE_Sensor1 != HE_Sensor1)
{
if(HE_Sensor1 > 0)
{
rpm = (1/(double)(rtime2-rtime1))*60000;
dwell = (1-((double)advance/360))*(rtime2-rtime1);
rtime1 = rtime2;
}
oHE_Sensor1 = HE_Sensor1;
}
if(rtime2 >= (rtime1 + dwell))
{
spark = 1;
sparkoff = rtime2 + 2;
}
if(rtime2 >= sparkoff)
{
spark = 0;
}
myfile << "\n";
Sleep(1);
}
myfile.close();
return 0;
}
void HEEmulator(void *arg)
{
int *rpmAd = (int*)arg;
int rpm = *rpmAd;
int milliseconds = (1/(double)rpm)*60000;
for(int i = 0; i < 10; i++)
{
*sensor = 1;
Sleep(milliseconds * 0.2);
*sensor = 0;
Sleep(milliseconds * 0.8);
}
*areRun = FALSE;
}
A desktop PC is not a real-time processing system.
When you use Sleep to pause a thread, you don't have any guarantees that it will wake up exactly after the specified amount of time has elapsed. The thread will be marked as ready to resume execution, but it may still have to wait for the OS to actually schedule it. From the documentation of the Sleep function:
Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses.
Also, the resolution of the system clock ticks is limited.
To more accurately simulate an ECU and the attached sensors, you should not use threads. Your simulation should not even depend on the passage of real time. Instead, use a single loop that updates the state of your simulation (both ECU and sensors) with each tick. This also means that your simulation should include the clock of the ECU.
I'm a beginner and I'm trying to reproduce a rae condition in order to familirize myself with the issue. In order to do that, I created the following program:
#include <Windows.h>
#include <iostream>
using namespace std;
#define numThreads 1000
DWORD __stdcall addOne(LPVOID pValue)
{
int* ipValue = (int*)pValue;
*ipValue += 1;
Sleep(5000ull);
*ipValue += 1;
return 0;
}
int main()
{
int value = 0;
HANDLE threads[numThreads];
for (int i = 0; i < numThreads; ++i)
{
threads[i] = CreateThread(NULL, 0, addOne, &value, 0, NULL);
}
WaitForMultipleObjects(numThreads, threads, true, INFINITE);
cout << "resulting value: " << value << endl;
return 0;
}
I added sleep inside a thread's function in order to reproduce the race condition as, how I understood, if I just add one as a workload, the race condition doesn't manifest itself: a thread is created, then it runs the workload and it happens to finish before the other thread which is created on the other iteration starts its workload. My problem is that Sleep() inside the workload seems to be ignored. I set the parameter to be 5sec and I expect the program to run at least 5 secs, but insted it finishes immediately. When I place Sleep(5000) inside main function, the program runs as expected (> 5 secs). Why is Sleep inside thread unction ignored?
But anyway, even if the Sleep() is ignored, the program outputs this everytime it is launched:
resulting value: 1000
while the correct answer should be 2000. Can you guess why is that happening?
WaitForMultipleObjects only allows waiting for up to MAXIMUM_WAIT_OBJECTS (which is currently 64) threads at a time. If you take that into account:
#include <Windows.h>
#include <iostream>
using namespace std;
#define numThreads MAXIMUM_WAIT_OBJECTS
DWORD __stdcall addOne(LPVOID pValue) {
int* ipValue=(int*)pValue;
*ipValue+=1;
Sleep(5000);
*ipValue+=1;
return 0;
}
int main() {
int value=0;
HANDLE threads[numThreads];
for (int i=0; i < numThreads; ++i) {
threads[i]=CreateThread(NULL, 0, addOne, &value, 0, NULL);
}
WaitForMultipleObjects(numThreads, threads, true, INFINITE);
cout<<"resulting value: "<<value<<endl;
return 0;
}
...things work much more as you'd expect. Whether you'll actually see results from the race condition is, of course, a rather different story--but on multiple runs, I do see slight variations in the resulting value (e.g., a low of around 125).
Jerry Coffin has the right answer, but just to save you typing:
#include <Windows.h>
#include <iostream>
#include <assert.h>
using namespace std;
#define numThreads 1000
DWORD __stdcall addOne(LPVOID pValue)
{
int* ipValue = (int*)pValue;
*ipValue += 1;
Sleep(5000);
*ipValue += 1;
return 0;
}
int main()
{
int value = 0;
HANDLE threads[numThreads];
for (int i = 0; i < numThreads; ++i)
{
threads[i] = CreateThread(NULL, 0, addOne, &value, 0, NULL);
}
DWORD Status = WaitForMultipleObjects(numThreads, threads, true, INFINITE);
assert(Status != WAIT_FAILED);
cout << "resulting value: " << value << endl;
return 0;
}
When things go wrong, make sure you've asserted the return value of any Windows API function that can fail. If you really badly need to wait on lots of threads, it is possible to overcome the 64-thread limit by chaining. I.e., for every additional 64 threads you need to wait on, you sacrifice a thread whose sole purpose is to wait on 64 other threads, and so on. We (Windows Developer's Journal) published an article demonstrating the technique years ago, but I can't recall the author name off the top of my head.