一、函數sigqueue
sigqueue函數原型:
函數作用:新的發送信號系統調用,主要是針對實時信號提出的支持信號帶有參數,與函數sigaction()配合使用
int sigqueue(pid_t pid, int signo, const union sigval value);
分析:
- 第一個參數:?指定接收信號的進程id
- 第二個參數:確定即將發送的信號
- 第三個參數:是一個聯合結構體union sigval,指定了信號傳遞的參數,即通常所說的4字節值?
二、程序清單
1. 測試代碼:
發送端程序代碼:
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>void handler(int, siginfo_t *, void*);int main(int argc, char *argv[])
{printf("I'm %d\n", getpid());struct sigaction act;act.sa_sigaction = handler;sigemptyset(&act.sa_mask);act.sa_flags = SA_SIGINFO;if(sigaction(SIGINT, &act, NULL) < 0) {perror("sigaction error");exit(0);}for(; ;)pause();return 0;
}void handler(int sig, siginfo_t *info, void *ctx)
{printf("recv a sig = %d data = %d data = %d\n", sig, info->si_value.sival_int, info->si_int);
}
接收端程序代碼:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>int main(int argc, char *argv[])
{if(argc != 2) {fprintf(stderr, "Usage %s pid\n", argv[0]);exit(0);}pid_t pid = atoi(argv[1]);union sigval v;v.sival_int = 100;sigqueue(pid, SIGINT, v);sleep(3);return 0;}
輸出結果
發送端:
接收端:
?
2. 測試代碼:
發送端程序:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>int main(int argc, char *argv[])
{if(argc != 2) {fprintf(stderr, "Usage %s pid\n", argv[0]);exit(0);}pid_t pid = atoi(argv[1]);union sigval v;v.sival_int = 100;sigqueue(pid, SIGINT, v);sigqueue(pid, SIGINT, v);sigqueue(pid, SIGINT, v);sigqueue(pid, SIGRTMIN, v);sigqueue(pid, SIGRTMIN, v);sigqueue(pid, SIGRTMIN, v);sleep(3);kill(pid, SIGUSR1);return 0;
}
接收端程序:
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>void handler(int sig);int main(int argc, char *argv[])
{printf("I'm %d\n", getpid());struct sigaction act;act.sa_sigaction = handler;sigemptyset(&act.sa_mask);act.sa_flags = 0;sigset_t s;sigemptyset(&s);sigaddset(&s, SIGINT);sigaddset(&s, SIGRTMIN);sigprocmask(SIG_BLOCK, &s, NULL);if(sigaction(SIGINT, &act, NULL) < 0) {perror("sigaction error");exit(0);}if(sigaction(SIGRTMIN, &act, NULL) < 0) {perror("sigaction error");exit(0);}if(sigaction(SIGUSR1, &act, NULL) < 0) {perror("sigaction error");exit(0);}for(; ;)pause();return 0;
}void handler(int sig)
{if(sig == SIGINT || sig == SIGRTMIN) printf("recv a sig = %d\n", sig);else if(sig == SIGUSR1){sigset_t s;sigemptyset(&s);sigaddset(&s, SIGINT);sigaddset(&s, SIGRTMIN);sigprocmask(SIG_UNBLOCK, &s, NULL); }
}
輸出結果:
發送端:
接收端: