C++ 跨进程发送信号

跨进程发送信号

接受信号的进程

// sig_wait.cpp
#include <iostream>
// #include <thread>
#include <csignal>
#include <unistd.h>
using namespace std;

void signal_handler_no_parameter()
{
    cout << "get signal : SIGURE1 " << endl;
    exit(1);
}

void signal_handler_int_parameter(int sig_num)
{
    cout << "get signal SIGUSR2 and sig_num = " << sig_num << endl;
    exit(1);
}

int main()
{
    signal(SIGUSR1, (sighandler_t)signal_handler_no_parameter);
    signal(SIGUSR2, signal_handler_int_parameter);

    while(true)
    {
        cout << "Waiting signal..." << endl;
        sleep(3);
    }

    return 0;
}

发送进程

// sig_send.cpp
#include <iostream>
#include <csignal>
#include <cstring>
#include <string>
#include <unistd.h>
using namespace std;

void get_cmd_result(const string &str_cmd, string &str_result)
{
    FILE* cmd_result = popen(str_cmd.c_str(), "r");

    char *buf = new char[256];
    memset(buf, 0 , sizeof(buf));

    fread(buf, 1, sizeof(buf), cmd_result);
    str_result = buf;

    pclose(cmd_result);
    delete buf;
    buf = nullptr;
}

int send_proc_USR1(const string &proc_name)
{
    string str_cmd = "ps -a | grep " + proc_name + " | grep -v grep | awk '{print $1}'";
    string proc_pid;

    get_cmd_result(str_cmd, proc_pid);
    cout << "proc_pid : " << proc_pid << endl;

    if(proc_pid.size() == 0)
    {
        cout << "There is no " << proc_name << " thread, and exit" << endl;
        return -1;
    }

    string str_emit_SIGUSR1_to_proc = "kill -USR1 " + proc_pid;
    cout << "execute cmd : " << str_emit_SIGUSR1_to_proc << endl;
    return system(str_emit_SIGUSR1_to_proc.c_str());

    return 0;
}

int main()
{
    while(true)
    {
        if(0 > send_proc_USR1("sig_wait")){
            break;
        }
        sleep(2);
    }

    return 0;
}
posted @ 2023-10-07 10:50  王清河  阅读(53)  评论(0编辑  收藏  举报