Get signal when tid status change

倾然丶 夕夏残阳落幕 提交于 2021-02-08 11:19:33

问题


There is a way to look when pid/tid status change with waitpid but this is blocking function.

I want to monitor all threads in specific pid and get signal when one of them change and print the tid.

For now I open threads as count of threads in that process and each 1 make waitpid on 1 tid and after that blocking function finish I print that tid that changed.

How can I get a signal that tid change so I can monitor all tid's in 1 thread.

I didn't want to monitor all pid in system only specific pid/tid.

Those tids/pids are not children of my process.


回答1:


You can call

int status;
pid_t waitpid(-1, &status, 0);

to wait for any child process change. So you do not have to specify in advance, which pid to monitor, and can react on any status change. This way you do not need to start one thread for each pid.

As to the signal part of your question: A SIGCHLD is sent to your process when a child process exits. This signal is ignored by default, but you can install a custom signal handler for it, of course.

If you only want to reap specific pids, linux provides the option WNOWAIT, which only reports the state, but does not really reap the child process. Now you can check, if the pid is one of those you want to monitor, and if so, call waitpid() again without the option.

If the processes are not children, waitpid() cannot be used in general. One option is, to attach with ptrace() to these 40 processes to get signalled, if one of these processes exit. This might have unwanted side-effects, however.




回答2:


If you're using POSIX threads, then you could use pthread_cleanup_push and pthread_cleanup_pop to call a "cleanup" function when your thread is exiting.

This "cleanup" function could then send one of the user signals (SIGUSR1 or SIGUSR2) to the process which then catches it and treats it as a signal about thread termination.

If you use sigqueue you can add the thread-id for the signal handler so it knows which thread just exited.

You can use pthread_sigmask to block the user signal in all threads, to make sure it's only delivered to the main process thread (or use pthread_sigqueue to send to the main process thread specifically).



来源:https://stackoverflow.com/questions/60203706/get-signal-when-tid-status-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!