1.信号发送端send.cpp
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <sys/time.h>
#include <stdlib.h>
#include <stdarg.h>
using namespace std;
#define MYSIG SIGUSR1
void print_time_info(const char *fmt, ...) {
struct tm tm;
struct timeval tv;
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm);
va_list args;
va_start(args, fmt);
fprintf(stdout, "[%04d-%02d-%02d %02d:%02d:%02d.%06u] ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, (unsigned int)tv.tv_usec);
vfprintf(stdout, fmt, args);
fprintf(stdout, "\n");
va_end(args);
}
void get_cmd_result(char* buf,int len,const string &cmd)
{
int chars_read = 0;
FILE *read_fp = NULL;
read_fp = popen(cmd.c_str(), "r");
if (read_fp != NULL)
{
chars_read = fread(buf, sizeof(char), len, read_fp);
buf[chars_read - 1] = 0;
printf("result:%s\n", buf);
pclose(read_fp);
}
}
int main(int argc,char** argv){
union sigval mysigval;
char id[10] = {0};
stringstream cmd;
pid_t pid;
if(argc < 2){
print_time_info("wrong arg!");
return -1;
}
cmd << "pidof " << argv[1];
get_cmd_result(id,10,cmd.str());
pid = atoi(id);
mysigval.sival_int = 7;
if(sigqueue(pid,MYSIG,mysigval) == -1){
print_time_info("sigqueue error!");
return -1;
}
print_time_info("send MYSIG success!");
return 0;
}
编译:g++ send.cpp -o send
2.信号接收端recv.cpp:
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define MYSIG SIGUSR1
void print_time_info(const char *fmt, ...) {
struct tm tm;
struct timeval tv;
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm);
va_list args;
va_start(args, fmt);
fprintf(stdout, "[%04d-%02d-%02d %02d:%02d:%02d.%06u] ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, (unsigned int)tv.tv_usec);
vfprintf(stdout, fmt, args);
fprintf(stdout, "\n");
va_end(args);
}
void mycb(int sig,siginfo_t* info,void* myact){
print_time_info("recv MYSIG!");
print_time_info("recv int arg:%d",info->si_int);
exit(0);
}
int main(int argc,char** argv){
struct sigaction myact;
myact.sa_flags = SA_SIGINFO;
myact.sa_sigaction = mycb;
if(sigaction(MYSIG,&myact,NULL) < 0){
print_time_info("sigaction fail!");
return -1;
}
while(1){
print_time_info("wait");
sleep(2);
}
return 0;
}
编译: g++ recv.cpp -o recv
3.执行
先执行recv,再执行send(./recv ,./send recv)
4.执行结果
# ./send recv
result:1722
[2017-09-11 11:46:02.280898] send MYSIG success!
# ./recv
[2017-09-11 11:45:59.360964] wait
[2017-09-11 11:46:01.361365] wait
[2017-09-11 11:46:02.280907] recv MYSIG!
[2017-09-11 11:46:02.280925] recv int arg:7
二,相关说明