- 在多进程的情况下,用kill给进程发信号,如果是给进程发信号,那么进程组里只有一个进程能收到,如果是给进程组发信号,那么每个进程都能接收到
#include <iostream>
#include <csignal>
#include <unistd.h>
using namespace std;
void signalHandler( int signum )
{
cout << "Interrupt signal (" << getpid() << ") received.\n";
sleep(10);
}
int main ()
{
int pid = fork();
// 注册信号 SIGINT 和信号处理程序
signal(SIGINT, signalHandler);
signal(SIGUSR1, signalHandler);
cout << "Going to sleep...." << endl;
while(1){
sleep(1);
}
return 0;
}
- 在多线程的情况下,不管是用pthread库还是c++的thread库,在mac上只有一个进程号,用geitid或者pthread_self可以拿到真正的进程的id,给进程的任意一个线程的SPID发信号是所有线程随机选择一个进行处理,并且响应时getpid是相同的进程号。给进程所在的进程组发信号同样的表现。
-
#include <iostream>
#include <csignal>
#include <thread>
#include <unistd.h>
using namespace std;
void signalHandler( int signum )
{
cout << "Interrupt signal (" << getpid() << ") received.\n";
sleep(10);
}
void threadRunner()
{
// int pid = fork();
// 注册信号 SIGINT 和信号处理程序
cout << "Signal register...." << endl;
signal(SIGINT, signalHandler);
signal(SIGUSR1, signalHandler);
cout << "Going to sleep...." << endl;
while(1){
sleep(1);
}
}
int main ()
{
thread th1(threadRunner);
thread th2(threadRunner);
th1.join();
th2.join();
return 0;
}
--------------------
void* threadRunner(void *)
{
// int pid = fork();
// 注册信号 SIGINT 和信号处理程序
cout << "Signal register...." << endl;
signal(SIGINT, signalHandler);
signal(SIGUSR1, signalHandler);
cout << "Going to sleep...." << endl;
while(1){
sleep(1);
}
return nullptr;
}
int main ()
{
pthread_t th1, th2;
pthread_create(&th1, nullptr, threadRunner, nullptr);
pthread_create(&th2, nullptr, threadRunner, nullptr);
pthread_join(th1, nullptr);
pthread_join(th2, nullptr);
return 0;
}