Auto Thread resume c++ - c++

i build Simple Anticheat module for a game and i need protect the Thread's from a Suspend (Like Suspend Thread from Processhacker).
Is there any way to automatically resume the thread if is suspended?
Here is my module code:
#include "stdafx.h"
#include "Start.h"
void Msg_Sf_Br(){
MessageBoxA(NULL,"SpeedHack - Detect", load.Nome_das_Janelas, MB_SERVICE_NOTIFICATION | MB_ICONWARNING);
ExitProcess(0);
}
void Msg_Sf_En(){
MessageBoxA(NULL,"SpeedHack - Detect", load.Nome_das_Janelas, MB_SERVICE_NOTIFICATION | MB_ICONWARNING);
ExitProcess(0);
}
void Speed_perf()
{
if( *(unsigned long*)QueryPerformanceCounter != 2337669003 ){
if (load.Log_Txt_Hack == 1){
}
if (load.Message_Warning_En == 1){
ExitProcess(0);
}
if (load.Message_Warning_En == 2){
CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(Msg_Sf_Br),NULL,0,0);
Sleep(3000);
ExitProcess(0);
}
if (load.Message_Warning_En == 0){
ExitProcess(0);
}
else
ExitProcess(0);
}
}
void performance(){
if (load.Anti_Kill_Scans == 1)
{
again:
Speed_perf();
Sleep(load.Detecta_Speed_PerformanceT);
goto again;
}
else
{
again2:
Speed_perf();
Sleep(load.Detecta_Speed_PerformanceT);
goto again2;
}
}
void SPerformance(){
CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(performance),NULL,0,0);
}
Any idea?

With a little trick you can hide your thread from any debugger or tools like process hacker.
void func()
{
}
int main()
{
int(__stdcall* ZwCreateThreadEx)(HANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, HANDLE, PVOID, PVOID, ULONG, ULONG_PTR, SIZE_T, SIZE_T, PVOID) = (decltype(ZwCreateThreadEx))GetProcAddress(GetModuleHandle("ntdll.dll"),"ZwCreateThreadEx");
HANDLE hThread=0;
ZwCreateThreadEx(&hThread,0x1FFFFF,0,GetCurrentProcess(),
(LPTHREAD_START_ROUTINE)func,0, 0x4/*hide flag*/,0,0x1000,0x10000,0);
return 0;
}

You can do it this way:
get list of process thread ids, using CreateToolhelp32Snapshot
go to first thread using methods: Thread32First.
for each found thread (you should check if belong to the given process):
then Open the thread using OpenThread in manner to retrieve handle to the thread from it thread id,
when you have the handle, you can suspend the thread using SuspendThread in manner to retrieve the previous suspension count,
then you can Resume the thread until it suspension count is 0. you must resume at least once in manner to cancel the suspension from the previous step.
if thread are not allowed to be suspended, you can use ResumeThread just to get the suspension count even if it was not suspended.
Close the thread handle using CloseHandle
iterate to next thread use Thread32Next.
In manner to be able to do the whole thing you must run as administrator.
Here is an example:
void TraverseProcessThreads(DWORD pid)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //get list of all system thread
if( hSnapshot == INVALID_HANDLE_VALUE)
{
//print error and return;
return;
}
THREADENTRY32 threadEntry;
if( Thread32First( hSnapshot, &threadEntry) )
{
size_t threadsCounter = 0, suspendedThreadsCounter=0;
do{
if(te.th32OwnerProcessID == pid) //we get all threads in system, should filter the relevant pid.
{
threadsCounter ++; //found thread
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS,FALSE,te.th32ThreadID); //get handle to thread from its thread id
if(hThread == NULL) //
{
//print error and break. (will be permission error if not administrator)
break;
}
int suspensionCount = SuspendThread( hThread ) ;//will return previous suspension count. you can also use ResumeThread if there's no way it can be suspended.
if(suspensionCount > 0)
{
//thread was suspended
suspendedThreadsCounter ++;
}
//cancel our suspension...
suspensionCount = ResumeThread(hThread );
/*to resume suspended thread use ResumeThread until it return 1.
do{
suspensionCount = ResumeThread(hThread );
}while (suspensionCount > 1); //similar to Suspend Resume return previous Suspention count.
*/
}
CloseHandle(hThread);
}while(Thread32Next( hSnapshot, &threadEntry) );
//print results:
cout<<"process id"<<pid<<endl<<" has "<<threadsCounter <<" threads " <<endl
<<suspendedThreadsCounter <<" threads was suspended"<<endl;
}
else{
//print some error...
}
CloseHandle(hSnapshot);
}

Related

pthread_join hangs forever C++

I am running this g_test where I simply initialize and close a client.
TEST(safIpc, createAndCloseClient)
{
std::shared_ptr<fnv::ipcsvc::IpcSvc> safIpc = std::make_shared<fnv::ipcsvc::IpcSvc>();
const std::string& app1 {"/testApp1"};
const std::string& groupName {"wir_clients"};
fnv::ipcsvc::IpcSvcAttrMq attr(fnv::ipcsvc::IpcSvcAttrType::MQ_CLIENT,
app1,
groupName,
"/server");
std::shared_ptr<IpcSvcTestSafHandler> msgHandler = std::make_shared<IpcSvcTestSafHandler>();
// initialize the ipc library
IpcSvcPriv::SharedPtr ipcPrivData {nullptr};
fnv::ipcsvc::IpcSvcRet ret = safIpc->init(attr, msgHandler, ipcPrivData);
EXPECT_EQ(ret, fnv::ipcsvc::IpcSvcRet::SUCCESS);
EXPECT_NE(ipcPrivData, nullptr);
ret = safIpc->close(ipcPrivData, app1); //HANGS here
EXPECT_EQ(fnv::ipcsvc::IpcSvcRet::SUCCESS, ret);
}
In init I create 3 threads: (here is the relevant part of the init code):
1- A process thread
2- a Receive thread
3- A timer thread
int rc = pthread_create(&m_timerThread,
NULL,
&IpcSvcImpl::timer_start,
this);
if (rc != 0)
{
ipcSvcLog(LOGE, "Failed to create timer thread!");
close(tmpPrivData,
attr.getAppId());
return error;
}
pthread_setname_np(m_timerThread,
"IpcSvcTimerThread");
}
// Start the worker threads
int rc = pthread_create(&m_receiveThread,
NULL,
&IpcSvcImpl::receive,
this);
if (rc != 0)
{
//TODO some error log
close(tmpPrivData,
attr.getAppId());
return error;
}
pthread_setname_np(m_receiveThread,
"IpcSvcReceiveThread");
rc = pthread_create(&m_processThread,
NULL,
&IpcSvcImpl::process,
this);
if (rc != 0)
{
//TODO some error log
close(tmpPrivData,
attr.getAppId());
return error;
}
pthread_setname_np(m_processThread,
"IpcSvcProcessThread");
Here is the close function:
IpcSvcRet IpcSvcImpl::close(IpcSvcPriv::SharedPtr privateData,
const std::string& appId)
{
if (!privateData)
{
//TODO log about client not providing sane private data
return IpcSvcRet::FAIL;
}
// acquire the mutex and set close called to true
{
std::lock_guard<std::mutex> guard(m_closeMtx);
m_closed = true;
}
if (m_msgQueue)
{
m_msgQueue->mutexInit();
// writing dummy message to process thread
std::pair<std::array<uint8_t, IPCSVC_MAX_MSG_SIZE>, ssize_t> queueMsg;
m_msgQueue->enqueue(queueMsg);
}
// writing dummy message to receive thread
uint32_t buffer = 0;
sendData(privateData,
(void*)&buffer,
sizeof(uint32_t),
appId);
pthread_join(m_receiveThread,
NULL);
pthread_join(m_processThread,
NULL);
if (m_isClient)
{
m_cv.notify_one();
printf("timer thread hangs\n"); // HANGS HERE ///////////////////////////////////////
pthread_join(m_timerThread,
NULL);
//This line is never reached..
}
delete m_msgQueue;
m_msgQueue = nullptr;
// close the ipc layer
if (m_ipc)
{
m_ipc->close();
delete m_ipc;
m_ipc = nullptr;
}
m_clientsList.clear();
m_hbManager = { };
return IpcSvcRet::SUCCESS;
}
Here is the timer_start function:
The timer thread is a timer that is keeps looping forever unless the fc->m_closed is set to true. It triggers fc->timerExpiry() every 2 seconds.
// timer thread entry
void* IpcSvcImpl::timer_start(void *arg)
{
if (!arg)
{
return nullptr;
}
printf("starting timer\n");
IpcSvcImpl* fc = static_cast<IpcSvcImpl *>(arg);
std::unique_lock<std::mutex> lock(fc->m_closeMtx);
while (!(fc->m_closed))
{
printf("Entering loop\n");
lock.unlock();
auto expireAt = std::chrono::steady_clock::now() +
std::chrono::seconds(fc->getTimerInterval());
fc->timerExpiry();
lock.lock();
printf("here?\n");
fc->m_cv.wait_until(lock, expireAt);
printf("Here 2\n");
}
printf("Exited loop\n\n");
return nullptr;
}
The output of the unittest:
[----------] 5 tests from safIpc
[ RUN ] safIpc.createAndCloseClient
starting timer
Entering loop
closing..
timer thread hangs
pthread join hangs forever, I am not sure why. The "here" prints are never hit, which seems odd.
Thanks for the help!

Windows Errorcode : 298 for Bounded buffer solution in vc++

I have encountered bounded buffer problem in my project, For solving
this, im using 2 semaphores Full and empty.
Write operation waits for empty semaphore signal and signals full
semaphore after finishing write.
Read operation waits for Full semaphore signal and signals Empty
semaphore after read.
Since im using blocking calls for read and write, each read and
write happens in sequence.
i'm implementing this in VC++ in windows, but im facing windows
errorcode:298 while signalling empty semaphore which says Too many posts were made to a semaphore.
what would be the possible causes for the error 'too may posts were
made to a semaphore' ?
List item
semaphore creation:
string semName = m_mqName;
semName.append(SEMAPHORE_FULL_NAME_SUFFIX);
cout<<"\n <MessageQueue<DType, size>::CreateMsgQSemaphores ()> Semaphore name = "<<semName<<endl;
m_mqFullSemaphore = CreateSemaphore(
NULL, // default security attributes
0, // initial count
size, // maximum count
semName.c_str()); //semaphore name
if (m_mqFullSemaphore == nullptr)
{
cout<<"ERROR::CreateSemaphore Failed, Name:"<<semName<<",error code:"<<GetLastError()<<endl;
CloseHandle(m_mqMutex); // close the existing m_mqMutex
createSemaphoresStatus = CreateMsgQSemaphoresFailedError;
}
else if (ERROR_ALREADY_EXISTS == GetLastError())
{
cout<<"\n <MessageQueue<DType, size>::CreateMsgQSemaphores ()>::WARNING: 'full' Semaphore exist.. "<<semName<<endl;
}
else
//cout<<"***INFO:: semaphore created: m_mqFullSemaphore= "<<m_mqFullSemaphore<<endl;
//------------------------------------------Empty semaphore creation--------------------------------------------//
semName = m_mqName;
semName.append(SEMAPHORE_EMPTY_NAME_SUFFIX);
//cout<<"\n <MessageQueue<DType, size>::CreateMsgQSemaphores ()> Semaphore name = "<<semName<<endl;
m_mqEmptySemaphore = CreateSemaphore(
NULL, // default security attributes
size, // initial count
size, // maximum count
semName.c_str()); // semaphore Name
if(m_mqEmptySemaphore == nullptr)
{
cout<<"\n <MessageQueue<DType, size>::CreateMsgQSemaphores ()>::ERROR: Create empty Semaphore failed.. "<<semName<<endl;
CloseHandle(m_mqMutex); // close the existing m_mqMutex
createSemaphoresStatus = CreateMsgQSemaphoresFailedError;
}
Consumer thread (reader in my project)
DWORD dwFullSemaphoreWaitResult = WaitForSingleObject(m_mqFullSemaphore,
timeoutVal);//wair for full semaphore
if(dwFullSemaphoreWaitResult== WAIT_OBJECT_0) // got the full semaphore
{
//proceed further
DWORD dwMutexWaitResult = WaitForSingleObject( m_mqMutex, timeoutVal); // no time-out interval
//Queue_Mutex_Handler mutexHandler(m_mqMutex);
//RAII
LOG_MSG("SUCCESS: to aquire m_mqFullSemaphore:"<<m_mqName);
switch (dwMutexWaitResult)
{
case WAIT_OBJECT_0: // got ownership of the mutex
{
LOG_MSG("SUCCESS: to aquire m_mqMutex:"<<m_mqName);
size_t qSize = 0;
if(! m_pMsgQueueImpl->Dequeue(destMsg,qSize))
{
LOG_MSG("SUCCESS: Reached here:"<<m_mqName);
LOG_MSG("ERROR: Dequeue failed, MSG Queue is Empty:"<< m_mqName);
//ReleaseMutex(m_mqMutex);
execResult = MQState_Queue_Empty_Error;
if(0 == ReleaseMutex(m_mqMutex))
{
LOG_MSG("Release mutex error:"<<GetLastError());
}
}
else
{
int semCount = 0;
LOG_MSG("MQ POP successful:"<< m_mqName<<", qSize="<<qSize);
//ReleaseMutex(m_mqMutex);
if(0 == ReleaseMutex(m_mqMutex))
{
LOG_MSG("Release mutex error:"<<GetLastError());
}
if ( 0 == ReleaseSemaphore(
m_mqEmptySemaphore, // handle to semaphore
1, // increase count by one
NULL)) // not interested in previous count
{
//LOG_MSG("semCount = "<<semCount);
LOG_MSG("Release Empty Semaphore error: "<<GetLastError());
}
else
{
//LOG_MSG("semCount = "<<semCount);
LOG_MSG("empty Semaphore signalled successfully");
}
return (int)qSize;
}
break;
}
case WAIT_TIMEOUT:
{
LOG_MSG("ERROR: Failed to aquire Mutex:"<<m_mqName<<", due to Timeout:"<<timeoutVal);
execResult = MQState_QOpTimeOut_Error;
break;
}
default: // The thread got ownership of an abandoned mutex
{
LOG_MSG("ERROR: Failed to aquire Mutex:"<<m_mqName<<", due to GetLastError:"<<GetLastError());
execResult = MQState_Queue_Unhandled_Error;
}
} // end of switch (dwMutexWaitResult)
}
else if(dwFullSemaphoreWaitResult == WAIT_TIMEOUT)
{
LOG_MSG("ERROR: Failed to aquire m_mqFullSemaphore:"<<m_mqName<<", due to Timeout:"<<timeoutVal);
execResult = MQState_QOpTimeOut_Error;
}
else
{
LOG_MSG("ERROR: Failed to aquire m_mqFullSemaphore:"<<m_mqName<<", GetLastError:"<<GetLastError());
execResult = MQState_Queue_Unhandled_Error;
}
if(execResult != MQState_QOp_Success)
return execResult;
//=================================================================================================
//LOG_FUNC_END;
return execResult;
Producer thread
MSG_QUEUE_STATUS execResult = MQState_QOp_Success;
//Wait for empty semaphore
DWORD dwSemaphoreWaitResult = WaitForSingleObject( m_mqEmptySemaphore, // handle to mutex
timeoutValInMs); // time-out interval
LOG_MSG("m_mqEmptySemaphore: "<<m_mqEmptySemaphore);
LOG_MSG("Got the m_mqEmptySemaphore");
//Wait for mutex
if(dwSemaphoreWaitResult == WAIT_OBJECT_0)
{
DWORD dwMutexWaitResult = WaitForSingleObject( m_mqMutex, // handle to mutex
timeoutValInMs); // time-out interval
//Queue_Mutex_Handler mutexHandler(m_mqMutex);
LOG_MSG("Got the m_mqMutex");
switch(dwMutexWaitResult)
{
case WAIT_OBJECT_0:
LOG_MSG("going to send Message");
if(m_pMsgQueueImpl->Enqueue(srcMsg) )
{
LOG_MSG("Message Sent successfully");
//int semCount;
if(0 == ReleaseMutex(m_mqMutex))
{
LOG_MSG("Release mutex error:"<<GetLastError());
}
if ( 0 == ReleaseSemaphore(
m_mqFullSemaphore, // handle to semaphore
1, // increase count by one
NULL)) // not interested in previous count
{
//LOG_MSG("semCount = "<<semCount);
LOG_MSG("Release full Semaphore error: "<<GetLastError());
}
else
{
//LOG_MSG("semCount = "<<semCount);
LOG_MSG("full Semaphore signalled successfully");
}
///++++++++++++++
}
else
{
LOG_MSG("ERROR: Enqueue failed, MSG Queue is Full, QName = "<< m_mqName);
if(0 == ReleaseMutex(m_mqMutex))
{
LOG_MSG("Release mutex error:"<<GetLastError());
}
execResult = MQState_Queue_Full_Error;
}
break;
case WAIT_TIMEOUT:
LOG_MSG("ERROR: Failed to aquire MsgQueue Mutex:"<<m_mqName<<", due to Timeout:"<<timeoutValInMs);
execResult = MQState_QOpTimeOut_Error;
break;
default:
LOG_MSG("ERROR: Failed to aquire MsgQueue Mutex:"<<m_mqName);
execResult = MQState_Queue_Unhandled_Error;
}//switch ends
}
else if(WAIT_TIMEOUT==dwSemaphoreWaitResult)
{
LOG_MSG("ERROR: Failed to aquire MsgQueue semaphore:"<<m_mqName<<", due to Timeout:"<<timeoutValInMs);
execResult = MQState_QOpTimeOut_Error;
}
else
{
LOG_MSG("ERROR: Failed to aquire MsgQueue semaphore:"<<m_mqName);
execResult = MQState_Queue_Unhandled_Error;
}
//RAII
//LOG_FUNC_END;
return execResult;

Call a function from a thread and RS 232

I am programming in Visual Studio 2008 in console application. I am working with a display that is communicated by Rs 232.
I have a thread that counts from 0 to 10 seconds. When reaches 10 I want to turn off the displays backlight. For that I have a function that is called from the thread. The called from the thread is well because I know that the code of the function is executed.
But code of turning the backlight off does not work when the function is called from the thread and it works the it is called from another place. Any ideas?
Thanks.
void FunctionBacklightoff(HANDLE portHandle,DWORD bytesTransmitted)
{
cout << "backoff";
WriteFile(portHandle, backlight_off , 4, &bytesTransmitted, NULL);//does not work when
//it is called from the thread. It works when it is called from wmain()
}
DWORD WINAPI solo_thread(void* arg)
{
int Counter = 0;
printf( "In second thread...\n" );
while ( true )
{
if(Counter<10)
{
Counter++;
Sleep(1000);
}
else
{
printf( "Han pasado 10 segundos; Counter:-> %d\n", Counter );
FunctionBacklightoff(portHandle,bytesTransmitted);//from here doesnt work
Counter = 0;
}
}
return 0;
}
int wmain(void)
{
hThread =CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);
//inicialize rs232 communications...
retVal = PortOpen(&portHandle, 115200);
if (!retVal)
{
printf("Could not open CoM port");
getchar();
}
else
{
printf("CoM port opened successfully");
retVal = FALSE;
}
FunctionBacklightoff(portHandle,bytesTransmitted);//from here works
}
How portHandle is declared? Looks like it's static field so thread could simply not get change that happen after it's creation. To be sure you could mark portHandle as volatile or change the order of operations:
//Open port so we will be sure that postHandle is populated before thread starts.
retVal = PortOpen(&portHandle, 115200);
hThread = CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);
Also you have a BUG that your wmain will exit before thread being executed. To fix that you should place following code right before wmain last bracket:
WaitForSingleObject(hThread, INFINITE);
Note that because your thread have while(true) without break condition it will run forever and each 10 seconds will switch off backlight. If this was not intentional add a break into else.

How to track a process on Unix C++?

I have a program(A) that starts another program(B).
What I want is when every time B receives signal A sends this signal to B and all child processes of B. I don't really know how to implement a few things here:
1). How do I determine that signal was sent to B?
2). How do I save this signal in variable?
3). How do I loop until B is alive?
int main() {
pid_t pid = fork();
int32_t num = 0;
if (pid == 0) {
static char *argv[] = {"main", NULL};
execv(argv[0], argv); //start program B
}
else{
while(/*B is alive*/){
//if program B receives signal
//I want to send this signal to B and all child processes,
//cause B doesn't handle any signals
if (/*B receives signal*/){
//save this signal to num.
kill(pid, num); //???
//send signal to parent
//useless cause it was already send to B?
fp = popen((("pgrep -P ") + string(num)).c_str(), "r");
//pgrep all child processes
std::vector<int> children;
while (fgets(buf, 128, fp) != NULL) //getting child pid
children.push_back(stoi(string(buf)));
for(auto a : children)
kill(a, num); //send signal to child
}
}
}
return 0;
}
I am afraid your question is really too broad and it involves too many topics. I will try anyway to help if possible.
About Signal handling. I usually spwan a separate thread in my program that is just dedicated to signal handling. In this way, I won't "disturb" the main execution.
About how to handle signals, please have a look to this code snippet:
void * threadSignalHandler (){
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
syslog(LOG_ERR, "sigwait failed");
exit(1);
}
switch (signo) {
case SIGHUP:
//Do your stuff here
break;
case SIGTERM:
//Do your stuff here
break;
default:
syslog(LOG_INFO, "unexpected signal %d\n", signo);
break;
}
}
return(0);
}
Again, as exaplined, I usually spawn a new basic thread and I do it with in this way:
int err;
pthread_t tid;
/*
* Restore SIGHUP default and block all signals.
*/
sa.sa_handler = SIG_DFL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0)
err_quit("%s: can′t restore SIGHUP default");
sigfillset(&mask);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
err_exit(err, "SIG_BLOCK error");
/*
* Create a thread to handle SIGHUP and SIGTERM.
*/
err = pthread_create(&tid, NULL, threadSignalHandler, 0);
if (err != 0)
err_exit(err, "can′t create thread");
So, to answer your 3 questions:
A) Use the code I provided, it is tested and I know it works.
B) Just
modify the thread handler to store the signal received (variable
signo)
C) Please have a look here, there are consolidated ways to do
it, according to posix standards
(Check if process exists given its pid)

Waitpid equivalent with timeout?

Imagine I have a process that starts several child processes. The parent needs to know when a child exits.
I can use waitpid, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in waitpid to exit gracefully and join it. It's nice to have things clean up themselves, but it may not be that big of a deal.
I can use waitpid with WNOHANG, and then sleep for some arbitrary time to prevent a busy wait. However then I can only know if a child has exited every so often. In my case it may not be super critical that I know when a child exits right away, but I'd like to know ASAP...
I can use a signal handler for SIGCHLD, and in the signal handler do whatever I was going to do when a child exits, or send a message to a different thread to do some action. But using a signal handler obfuscates the flow of the code a little bit.
What I'd really like to do is use waitpid on some timeout, say 5 sec. Since exiting the process isn't a time critical operation, I can lazily signal the thread to exit, while still having it blocked in waitpid the rest of the time, always ready to react. Is there such a call in linux? Of the alternatives, which one is best?
EDIT:
Another method based on the replies would be to block SIGCHLD in all threads with pthread \ _sigmask(). Then in one thread, keep calling sigtimedwait() while looking for SIGCHLD. This means that I can time out on that call and check whether the thread should exit, and if not, remain blocked waiting for the signal. Once a SIGCHLD is delivered to this thread, we can react to it immediately, and in line of the wait thread, without using a signal handler.
Don't mix alarm() with wait(). You can lose error information that way.
Use the self-pipe trick. This turns any signal into a select()able event:
int selfpipe[2];
void selfpipe_sigh(int n)
{
int save_errno = errno;
(void)write(selfpipe[1], "",1);
errno = save_errno;
}
void selfpipe_setup(void)
{
static struct sigaction act;
if (pipe(selfpipe) == -1) { abort(); }
fcntl(selfpipe[0],F_SETFL,fcntl(selfpipe[0],F_GETFL)|O_NONBLOCK);
fcntl(selfpipe[1],F_SETFL,fcntl(selfpipe[1],F_GETFL)|O_NONBLOCK);
memset(&act, 0, sizeof(act));
act.sa_handler = selfpipe_sigh;
sigaction(SIGCHLD, &act, NULL);
}
Then, your waitpid-like function looks like this:
int selfpipe_waitpid(void)
{
static char dummy[4096];
fd_set rfds;
struct timeval tv;
int died = 0, st;
tv.tv_sec = 5;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(selfpipe[0], &rfds);
if (select(selfpipe[0]+1, &rfds, NULL, NULL, &tv) > 0) {
while (read(selfpipe[0],dummy,sizeof(dummy)) > 0);
while (waitpid(-1, &st, WNOHANG) != -1) died++;
}
return died;
}
You can see in selfpipe_waitpid() how you can control the timeout and even mix with other select()-based IO.
Fork an intermediate child, which forks the real child and a timeout process and waits for all (both) of its children. When one exits, it'll kill the other one and exit.
pid_t intermediate_pid = fork();
if (intermediate_pid == 0) {
pid_t worker_pid = fork();
if (worker_pid == 0) {
do_work();
_exit(0);
}
pid_t timeout_pid = fork();
if (timeout_pid == 0) {
sleep(timeout_time);
_exit(0);
}
pid_t exited_pid = wait(NULL);
if (exited_pid == worker_pid) {
kill(timeout_pid, SIGKILL);
} else {
kill(worker_pid, SIGKILL); // Or something less violent if you prefer
}
wait(NULL); // Collect the other process
_exit(0); // Or some more informative status
}
waitpid(intermediate_pid, 0, 0);
Surprisingly simple :)
You can even leave out the intermediate child if you're sure no other module in the program is spwaning child processes of its own.
This is an interesting question.
I found sigtimedwait can do it.
EDIT 2016/08/29:
Thanks for Mark Edington's suggestion. I'v tested your example on Ubuntu 16.04, it works as expected.
Note: this only works for child processes. It's a pity that seems no equivalent way of Window's WaitForSingleObject(unrelated_process_handle, timeout) in Linux/Unix to get notified of unrelated process's termination within timeout.
OK, Mark Edington's sample code is here:
/* The program creates a child process and waits for it to finish. If a timeout
* elapses the child is killed. Waiting is done using sigtimedwait(). Race
* condition is avoided by blocking the SIGCHLD signal before fork().
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
static pid_t fork_child (void)
{
int p = fork ();
if (p == -1) {
perror ("fork");
exit (1);
}
if (p == 0) {
puts ("child: sleeping...");
sleep (10);
puts ("child: exiting");
exit (0);
}
return p;
}
int main (int argc, char *argv[])
{
sigset_t mask;
sigset_t orig_mask;
struct timespec timeout;
pid_t pid;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0) {
perror ("sigprocmask");
return 1;
}
pid = fork_child ();
timeout.tv_sec = 5;
timeout.tv_nsec = 0;
do {
if (sigtimedwait(&mask, NULL, &timeout) < 0) {
if (errno == EINTR) {
/* Interrupted by a signal other than SIGCHLD. */
continue;
}
else if (errno == EAGAIN) {
printf ("Timeout, killing child\n");
kill (pid, SIGKILL);
}
else {
perror ("sigtimedwait");
return 1;
}
}
break;
} while (1);
if (waitpid(pid, NULL, 0) < 0) {
perror ("waitpid");
return 1;
}
return 0;
}
If your program runs only on contemporary Linux kernels (5.3 or later), the preferred way is to use pidfd_open (https://lwn.net/Articles/789023/ https://man7.org/linux/man-pages/man2/pidfd_open.2.html).
This system call returns a file descriptor representing a process, and then you can select, poll or epoll it, the same way you wait on other types of file descriptors.
For example,
int fd = pidfd_open(pid, 0);
struct pollfd pfd = {fd, POLLIN, 0};
poll(&pfd, 1, 1000) == 1;
The function can be interrupted with a signal, so you could set a timer before calling waitpid() and it will exit with an EINTR when the timer signal is raised. Edit: It should be as simple as calling alarm(5) before calling waitpid().
I thought that select will return EINTR when SIGCHLD signaled by on of the child.
I belive this should work:
while(1)
{
int retval = select(0, NULL, NULL, NULL, &tv, &mask);
if (retval == -1 && errno == EINTR) // some signal
{
pid_t pid = (waitpid(-1, &st, WNOHANG) == 0);
if (pid != 0) // some child signaled
}
else if (retval == 0)
{
// timeout
break;
}
else // error
}
Note: you can use pselect to override current sigmask and avoid interrupts from unneeded signals.
Instead of calling waitpid() directly, you could call sigtimedwait() with SIGCHLD (which would be sended to the parent process after child exited) and wait it be delived to the current thread, just as the function name suggested, a timeout parameter is supported.
please check the following code snippet for detail
static bool waitpid_with_timeout(pid_t pid, int timeout_ms, int* status) {
sigset_t child_mask, old_mask;
sigemptyset(&child_mask);
sigaddset(&child_mask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
printf("*** sigprocmask failed: %s\n", strerror(errno));
return false;
}
timespec ts;
ts.tv_sec = MSEC_TO_SEC(timeout_ms);
ts.tv_nsec = (timeout_ms % 1000) * 1000000;
int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
int saved_errno = errno;
// Set the signals back the way they were.
if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
printf("*** sigprocmask failed: %s\n", strerror(errno));
if (ret == 0) {
return false;
}
}
if (ret == -1) {
errno = saved_errno;
if (errno == EAGAIN) {
errno = ETIMEDOUT;
} else {
printf("*** sigtimedwait failed: %s\n", strerror(errno));
}
return false;
}
pid_t child_pid = waitpid(pid, status, WNOHANG);
if (child_pid != pid) {
if (child_pid != -1) {
printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
} else {
printf("*** waitpid failed: %s\n", strerror(errno));
}
return false;
}
return true;
}
Refer: https://android.googlesource.com/platform/frameworks/native/+/master/cmds/dumpstate/DumpstateUtil.cpp#46
If you're going to use signals anyways (as per Steve's suggestion), you can just send the signal manually when you want to exit. This will cause waitpid to return EINTR and the thread can then exit. No need for a periodic alarm/restart.
Due to circumstances I absolutely needed this to run in the main thread and it was not very simple to use the self-pipe trick or eventfd because my epoll loop was running in another thread. So I came up with this by scrounging together other stack overflow handlers. Note that in general it's much safer to do this in other ways but this is simple. If anyone cares to comment about how it's really really bad then I'm all ears.
NOTE: It is absolutely necessary to block signals handling in any thread save for the one you want to run this in. I do this by default as I believe it messy to handle signals in random threads.
static void ctlWaitPidTimeout(pid_t child, useconds_t usec, int *timedOut) {
int rc = -1;
static pthread_mutex_t alarmMutex = PTHREAD_MUTEX_INITIALIZER;
TRACE("ctlWaitPidTimeout: waiting on %lu\n", (unsigned long) child);
/**
* paranoid, in case this was called twice in a row by different
* threads, which could quickly turn very messy.
*/
pthread_mutex_lock(&alarmMutex);
/* set the alarm handler */
struct sigaction alarmSigaction;
struct sigaction oldSigaction;
sigemptyset(&alarmSigaction.sa_mask);
alarmSigaction.sa_flags = 0;
alarmSigaction.sa_handler = ctlAlarmSignalHandler;
sigaction(SIGALRM, &alarmSigaction, &oldSigaction);
/* set alarm, because no alarm is fired when the first argument is 0, 1 is used instead */
ualarm((usec == 0) ? 1 : usec, 0);
/* wait for the child we just killed */
rc = waitpid(child, NULL, 0);
/* if errno == EINTR, the alarm went off, set timedOut to true */
*timedOut = (rc == -1 && errno == EINTR);
/* in case we did not time out, unset the current alarm so it doesn't bother us later */
ualarm(0, 0);
/* restore old signal action */
sigaction(SIGALRM, &oldSigaction, NULL);
pthread_mutex_unlock(&alarmMutex);
TRACE("ctlWaitPidTimeout: timeout wait done, rc = %d, error = '%s'\n", rc, (rc == -1) ? strerror(errno) : "none");
}
static void ctlAlarmSignalHandler(int s) {
TRACE("ctlAlarmSignalHandler: alarm occured, %d\n", s);
}
EDIT: I've since transitioned to using a solution that integrates well with my existing epoll()-based eventloop, using timerfd. I don't really lose any platform-independence since I was using epoll anyway, and I gain extra sleep because I know the unholy combination of multi-threading and UNIX signals won't hurt my program again.
I can use a signal handler for SIGCHLD, and in the signal handler do whatever I was going to do when a child exits, or send a message to a different thread to do some action. But using a signal handler obfuscates the flow of the code a little bit.
In order to avoid race conditions you should avoid doing anything more complex than changing a volatile flag in a signal handler.
I think the best option in your case is to send a signal to the parent. waitpid() will then set errno to EINTR and return. At this point you check for waitpid return value and errno, notice you have been sent a signal and take appropriate action.
If a third party library is acceptable then the libkqueue project emulates kqueue (the *BSD eventing system) and provides basic process monitoring with EVFILT_PROC + NOTE_EXIT.
The main advantages of using kqueue or libkqueue is that it's cross platform, and doesn't have the complexity of signal handling. If your program is utilises async I/O you may also find it a lower friction interface than using something like epoll and the various *fd functions (signalfd, eventfd, pidfd etc...).
#include <stdio.h>
#include <stdint.h>
#include <sys/event.h> /* kqueue header */
#include <sys/types.h> /* for pid_t */
/* Link with -lkqueue */
int waitpid_timeout(pid_t pid, struct timespec *timeout)
{
struct kevent changelist, eventlist;
int kq, ret;
/* Populate a changelist entry (an event we want to be notified of) */
EV_SET(&changelist, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
kq = kqueue();
/* Call kevent with a timeout */
ret = kevent(kq, &changelist, 1, &eventlist, 1, timeout);
/* Kevent returns 0 on timeout, the number of events that occurred, or -1 on error */
switch (ret) {
case -1:
printf("Error %s\n", strerror(errno));
break;
case 0:
printf("Timeout\n");
break;
case 1:
printf("PID %u exited, status %u\n", (unsigned int)eventlist.ident, (unsigned int)eventlist.data);
break;
}
close(kq);
return ret;
}
Behind the scenes on Linux libkqueue uses either pidfd on Linux kernels >= 5.3 or a waiter thread that listens for SIGCHLD and notifies one or more kqueue instances when a process exits. The second approach is not efficient (it scans PIDs that interest has been registered for using waitid), but that doesn't matter unless you're waiting on large numbers of PIDs.
EVFILT_PROC support has been included in kqueue since its inception, and in libkqueue since v2.5.0.