can anyone debug this code for me regarding a watchdog timer in win ce? - windows-ce

#include <windows.h>
#include <pkfuncs.h>
#define WATCHDOG_NAME L"wd_critproc"
#define WATCHDOG_PERIOD 5000 // milliseconds
#define WATCHDOG_WAIT_TIME 2000 // milliseconds
//WDOG_NO_DFLT_ACTION, WDOG_KILL_PROCESS, WDOG_RESET_DEVICE
#define WATCHDOG_DEFAULT_ACTION WDOG_RESET_DEVICE
#define MAX_COUNT 10
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
{
HANDLE hWatchDogTimer=NULL;
LPCWSTR pszWatchDogName=WATCHDOG_NAME;
DWORD dwPeriod=WATCHDOG_PERIOD;
DWORD dwWait=WATCHDOG_WAIT_TIME;
DWORD dwDefaultAction=WATCHDOG_DEFAULT_ACTION;
DWORD dwCount=0;
BOOL bRet=FALSE;
wprintf((TEXT("[critproc] Critical process start\r\n")));
wprintf((TEXT("[critproc] Calling CreateWatchDogTimer...\r\n")));
//createwatchdogtimer api is being called here
hWatchDogTimer =
CreateWatchDogTimer(pszWatchDogName, dwPeriod,dwWait, dwDefaultAction,0,0);
if (! hWatchDogTimer)
{
wprintf((TEXT("[critproc] Invalid NULL handle, leaving app\r\n")));
return 1;
}
//checking if the error already exists then same watchdog timer is not called
if (GetLastError()==ERROR_ALREADY_EXISTS)
{
wprintf((TEXT("[critproc] WatchDog with this name already exists,
leaving app\r\n")));
return 1;
}
wprintf((TEXT("[critproc] Valid handle returned [0x%08x]\r\n")),
hWatchDogTimer);
wprintf((TEXT("[critproc] Starting watchdog timer...\r\n")));
bRet = StartWatchDogTimer(hWatchDogTimer,0);
if (! bRet)
{
wprintf((TEXT("[critproc] StartWatchDogTimer failed,
GetLastError returned 0x%x\r\n")),GetLastError());
CloseHandle(hWatchDogTimer);
return 1;
}
wprintf((TEXT("[critproc] Watchdog timer started successfully\r\n")));
dwCount=0;
while ((dwCount++)<MAX_COUNT)
{
BOOL bRetVal=0;
wprintf((TEXT("[critproc] Refreshing watchdog timer... [%d]\r\n")),dwCount);
bRetVal = RefreshWatchDogTimer(hWatchDogTimer,0);
if (!bRetVal)
{
wprintf((TEXT("[critproc] Failed to refresh watchdog timer,
GetLastError returned 0x%x\r\n")),GetLastError());
CloseHandle(hWatchDogTimer);
return 1;
}
Sleep(1000);
}
wprintf((TEXT("[critproc] Stopping watchdog timer refresh\r\n")));
dwCount=0;
while (++dwCount)
{
wprintf((TEXT("[critproc] The watchdog should timeout in \
a few seconds... [%d]\r\n")),dwCount);
Sleep(1000);
}
wprintf((TEXT("[critproc] Leaving app (should never be here)\r\n")));
CloseHandle(hWatchDogTimer);
return 0;
}

the error i'm getting is regarding the wmain function saying local function definitions are illegal –
You are not asking for debugging but for fixing compilation bug!
Sleep(1000);
}
^~~~~~~ this is what compiler is complaining about

Try properly defining main:
int _tmain(int argc, TCHAR* argv[])

Related

how to stop a thread that worked in infinity loop from another thread linux(c language)?

in main, I create two threads
thread 1 for the first func
thread 2 for second func2 (it included while(1))
i try to stop func2 from func by using pthread_cancel()
but didn't work and after I finish with func the Linux return to func2 and continue the infinite loop
is there a way to stop a thread that worked with an infinite loop from another thread ????
I think you need pthread_exit();
#include <pthread.h>
void pthread_exit(void *rval_ptr);
So we see that this function accepts only one argument, which is the return from the thread that calls this function. This return value is accessed by the parent thread which is waiting for this thread to terminate. The return value of the thread terminated by pthread_exit() function is accessible in the second argument of the pthread_join which just explained above.
You can see this example below:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int ret1,ret2;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
pthread_t id = pthread_self();
for(i=0; i<(0xFFFFFFFF);i++);
if(pthread_equal(id,tid[0]))
{
printf("\n First thread processing done\n");
ret1 = 100;
pthread_exit(&ret1);
}
else
{
printf("\n Second thread processing done\n");
ret2 = 200;
pthread_exit(&ret2);
}
return NULL;
}
int main(void)
{
int i = 0;
int err;
int *ptr[2];
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
i++;
}
pthread_join(tid[0], (void**)&(ptr[0]));
pthread_join(tid[1], (void**)&(ptr[1]));
printf("\n return value from first thread is [%d]\n", *ptr[0]);
printf("\n return value from second thread is [%d]\n", *ptr[1]);
return 0;
}

How to prematurely kill std::async threads before they are finished *without* using a std::atomic_bool?

I have a function that takes a callback, and used it to do work on 10 separate threads. However, it is often the case that not all of the work is needed. For example, if the desired result is obtained on the third thread, it should stop all work being done on of the remaining alive threads.
This answer here suggests that it is not possible unless you have the callback functions take an additional std::atomic_bool argument, that signals whether the function should terminate prematurely.
This solution does not work for me. The workers are spun up inside a base class, and the whole point of this base class is to abstract away details of multithreading. How can I do this? I am anticipating that I will have to ditch std::async for something more involved.
#include <iostream>
#include <future>
#include <vector>
class ABC{
public:
std::vector<std::future<int> > m_results;
ABC() {};
~ABC(){};
virtual int callback(int a) = 0;
void doStuffWithCallBack();
};
void ABC::doStuffWithCallBack(){
// start working
for(int i = 0; i < 10; ++i)
m_results.push_back(std::async(&ABC::callback, this, i));
// analyze results and cancel all threads when you get the 1
for(int j = 0; j < 10; ++j){
double foo = m_results[j].get();
if ( foo == 1){
break; // but threads continue running
}
}
std::cout << m_results[9].get() << " <- this shouldn't have ever been computed\n";
}
class Derived : public ABC {
public:
Derived() : ABC() {};
~Derived() {};
int callback(int a){
std::cout << a << "!\n";
if (a == 3)
return 1;
else
return 0;
};
};
int main(int argc, char **argv)
{
Derived myObj;
myObj.doStuffWithCallBack();
return 0;
}
I'll just say that this should probably not be a part of a 'normal' program, since it could leak resources and/or leave your program in an unstable state, but in the interest of science...
If you have control of the thread loop, and you don't mind using platform features, you could inject an exception into the thread. With posix you can use signals for this, on Windows you would have to use SetThreadContext(). Though the exception will generally unwind the stack and call destructors, your thread may be in a system call or other 'non-exception safe place' when the exception occurs.
Disclaimer: I only have Linux at the moment, so I did not test the Windows code.
#if defined(_WIN32)
# define ITS_WINDOWS
#else
# define ITS_POSIX
#endif
#if defined(ITS_POSIX)
#include <signal.h>
#endif
void throw_exception() throw(std::string())
{
throw std::string();
}
void init_exceptions()
{
volatile int i = 0;
if (i)
throw_exception();
}
bool abort_thread(std::thread &t)
{
#if defined(ITS_WINDOWS)
bool bSuccess = false;
HANDLE h = t.native_handle();
if (INVALID_HANDLE_VALUE == h)
return false;
if (INFINITE == SuspendThread(h))
return false;
CONTEXT ctx;
ctx.ContextFlags = CONTEXT_CONTROL;
if (GetThreadContext(h, &ctx))
{
#if defined( _WIN64 )
ctx.Rip = (DWORD)(DWORD_PTR)throw_exception;
#else
ctx.Eip = (DWORD)(DWORD_PTR)throw_exception;
#endif
bSuccess = SetThreadContext(h, &ctx) ? true : false;
}
ResumeThread(h);
return bSuccess;
#elif defined(ITS_POSIX)
pthread_kill(t.native_handle(), SIGUSR2);
#endif
return false;
}
#if defined(ITS_POSIX)
void worker_thread_sig(int sig)
{
if(SIGUSR2 == sig)
throw std::string();
}
#endif
void init_threads()
{
#if defined(ITS_POSIX)
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = worker_thread_sig;
sigaction(SIGUSR2, &sa, 0);
#endif
}
class tracker
{
public:
tracker() { printf("tracker()\n"); }
~tracker() { printf("~tracker()\n"); }
};
int main(int argc, char *argv[])
{
init_threads();
printf("main: starting thread...\n");
std::thread t([]()
{
try
{
tracker a;
init_exceptions();
printf("thread: started...\n");
std::this_thread::sleep_for(std::chrono::minutes(1000));
printf("thread: stopping...\n");
}
catch(std::string s)
{
printf("thread: exception caught...\n");
}
});
printf("main: sleeping...\n");
std::this_thread::sleep_for(std::chrono::seconds(2));
printf("main: aborting...\n");
abort_thread(t);
printf("main: joining...\n");
t.join();
printf("main: exiting...\n");
return 0;
}
Output:
main: starting thread...
main: sleeping...
tracker()
thread: started...
main: aborting...
main: joining...
~tracker()
thread: exception caught...
main: exiting...

pthread_cancel and cancellation point

I'm learning the pthread_cancel function and testing whether thread would be cancelled when it doesn't reach cancellation point. Thread is created by default attribute and make it running in add loop. But when cancellation request was sent and thread exit immediately. It doesn't reach cancellation point and I think it should not respond to the request immediately.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *thread_func(void *arg)
{
int i;
int j;
int k;
k = 1;
/* add operation */
for (i=0; i<1000; ++i) {
for (j=0; j<10000;++j) {
++k; // maybe for(z=0; z<10000; ++z) added would
// be better
}
}
return (void *)10;
}
int main(void)
{
char *retval;
pthread_t tid;
if (pthread_create(&tid, NULL, thread_func, NULL) != 0) {
printf("create error\n");
}
if (pthread_cancel(tid) != 0) { // cancel thread
printf("cancel error\n");
}
pthread_join(tid, (void **)retval);
printf("main thread exit\n");
return 0;
}
To have a "cancellation point" you need to use pthread_setcancelstate() to disable cancellation at the start of your thread function and then enable it when you want. When a new thread is spawned, it has the cancel state "enabled" meaning it can be canceled immediately at any time.
Perhaps more to the point, you probably shouldn't use pthread_cancel() at all. For more on that, see here: Cancelling a thread using pthread_cancel : good practice or bad
Cancelling a thread never means that it will immediately cancel anything which is running. It would just post a request to that thread. pthread_cancel only cancels a thread at a cancellation point. The list of cancellation points are defined in the man page of pthreads. In the above thread, you don't have any code which is a cancellation point. So the thread will always complete and will never get canceled. You can increase the loop or put a print statement at the last line of your thread and you will see that it is always completing the thread.
But, if you change the below code to add usleep (it is one of the cancellation point as defined in the man pages), you can see that the thread terminates after usleep. Even if you run any number of times, the thread will only get terminated at the cancellation point that is immediately after usleep and not any other point.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *thread_func(void *arg)
{
int i;
int j;
int k;
k = 1;
/* add operation */
for (i=0; i<1000; ++i) {
printf("Before - %d\n", i);
usleep(1);
printf("After - %d\n", i);
for (j=0; j<10000;++j) {
++k; // maybe for(z=0; z<10000; ++z) added would
// be better
}
printf("Never - %d\n", i);
}
printf("Normal Exit of thread\n");
return (void *)10;
}
int main(void)
{
char *retval;
pthread_t tid;
if (pthread_create(&tid, NULL, thread_func, NULL) != 0) {
printf("create error\n");
}
usleep(1000);
if (pthread_cancel(tid) != 0) { // cancel thread
printf("cancel error\n");
}
pthread_join(tid, (void **)retval);
printf("main thread exit\n");
return 0;
}

linux: alarm function doesn't work sometimes?

My code is as follows,The first time ,alarm works very well and handler2() function can work. however, the alarm doesn't work after it implement "doMain()" in the "handler2()".
I mean after the second time print ""In main Pleasae input: \n"", handler2() doesn't wrok anymore.
I don't know why? My code as follows:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#define MAX_LEN_COMM 64
jmp_buf jumper;
int stop =0; //o is not stop ,otherwise is stop;
void hanlder2();
void doMain();
void handler2()
{
int len_command = 0;
char character;
char commandStr[60];
printf("******************************\n");
printf("In Alarm Pleasae input: \n");
while((character=getchar())!='\n')
{
commandStr[len_command]=character;
len_command++;
}
commandStr[len_command]='\0';
printf("In Alarm input is %s\n",commandStr);
if (strcmp(commandStr,"N")==0||strcmp(commandStr,"n")==0){
printf("In Alarm You put no, we will stop alarm \n");
stop=1;
longjmp(jumper, 2);
}
else if(strcmp(commandStr,"Y")==0||strcmp(commandStr,"y")==0){
printf("In Alarm You put yes, we will continue alarm \n");
signal(SIGALRM, handler2);
alarm(5);
doMain();
}
}
void doMain(){
while(1){
setjmp(jumper);
if(stop==0){
signal(SIGALRM, handler2);
printf("return time %d\n",alarm(5));
}
int len_command = 0;
char character;
char commandStr[60];
printf("In main Pleasae input: \n");
while((character=getchar())!='\n')
{
commandStr[len_command]=character;
len_command++;
}
commandStr[len_command]='\0';
printf("In main input is %s\n",commandStr);
if (strcmp(commandStr,"N")==0||strcmp(commandStr,"n")==0){
printf("In main You put no\n");
}
else if(strcmp(commandStr,"Y")==0||strcmp(commandStr,"y")==0){
printf("In main You put yes\n");
}
}
}
void main()
{
doMain();
}
What you are doing is very wrong.
First, the signature of the handler should be void handler(int sig).
Second, there are very few functions that are safe to use within a handler so you should try to get out of a handler as quickly as possible and definitely not doing console i/o. You are using several unsafe library functions.
Lastly a signal handler is a function. It runs and returns to where your program was interrupted by the signal. During the time a handler runs signals of the same type are not deliverd. By calling doMain() from the handler - which is crazy - the handler never ends. Because it doesn't end you won't see any more alarm signals.

Qt - Close QThreads that are blocked by system-level calls

I have a thread which blocks until data is received from a system resources such as a USB device. I chose this model because the amount of data may vary, and data may be received at any time. Upon exiting the application, I get the message “QThread: Destroyed while thread is still running”. How should I go about closing these threads?
I’ve looked at other problems/solutions such as:
http://www.qtcentre.org/threads/14429-Loop-inside-Qthread-causes-quot-QThread-Destroyed-while-thread-is-still-running-quot
http://www.qtcentre.org/threads/6211-QThread-Destroyed-while-thread-is-still-running
The first solution involves using a flag (included in my code) however my thread will never reach the flag check.
The second solution uses QWaitCondition but seem to be along the same lines as the first.
I’ve included a stripped down version of the code below. The system calls WaitForSingleObject() is a substitute for what I actually use (GetOverlappedResult()).
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <QObject>
#include <QThread>
#include <QReadWriteLock>
#include <QDebug>
#ifdef Q_OS_WIN
#include <windows.h>
#endif // Q_OS_WIN
#ifdef Q_OS_LINUX
#include <unistd.h>
#endif // Q_OS_LINUX
////////////////////////////////////////////////
//
// Worker Object
//
////////////////////////////////////////////////
class Worker : public QObject {
Q_OBJECT
public:
QReadWriteLock lock;
bool running;
public slots:
void loop() {
qDebug() << "entering the loop";
bool _running;
forever {
lock.lockForRead();
_running = running;
lock.unlock();
if (!_running) return;
qDebug() << "loop iteration";
#ifdef Q_OS_WIN
HANDLE event = CreateEvent(NULL, FALSE, FALSE, NULL);
WaitForSingleObject(event, INFINITE);
#endif // Q_OS_WIN
#ifdef Q_OS_LINUX
read(0, 0, 1);
#endif // Q_OS_LINUX
}
}
};
////////////////////////////////////////////////
//
// Controller
//
////////////////////////////////////////////////
class Controller {
public:
Controller() {
myWorker.connect(&myThread, SIGNAL(started()), &myWorker, SLOT(loop()));
myWorker.moveToThread(&myThread);
myThread.start();
}
~Controller() {
// Safely close threads
myWorker.lock.lockForWrite();
myWorker.running = false;
myWorker.lock.unlock();
myThread.quit();
//myThread.wait();
//myThread.exit();
//myThread.terminate();
}
private:
QThread myThread;
Worker myWorker;
};
#endif // CONTROLLER_H
For Linux:
Sending a signal to the thread with pthread_kill() interrupted read() with failure code EINTR. sigaction() was used to register the signal, and the signal thrown was SIGUSR1.
// Global scope
void nothing(int signum) {}
...
// Within the start of the thread
pthread_t myThreadID = pthread_self(); // Get the thread ID
struct sigaction action;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
action.sa_handler = nothing;
sigaction(SIGUSR1, &action, NULL);
...
// When it's time to close the thread
pthread_kill(myThreadID, SIGUSR1);
For Windows:
Signaling the OVERLAPPED's hEvent with SetEvent() was used to unblock GetOverlappedResult().
// Store a reference to the event
HANDLE myEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
...
// Within the start of the thread
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = myEvent;
...
// When it's time to close the thread
SetEvent(myEvent);

Resources