进程间的通信(二)

编写程序实现以下功能:

进程A向进程B发送SIGUSR1信号;
进程B收到信号后,打印字符串“receive SIGUSR1”;
要求用sigqueue函数和sigaction函数实现以上功能;

sigaction和signal两个函数都是信号安装函数,但是他们两个之间还是有一定的区别的。

signal不能传递除信号之外的信息,而sigaction能够传递额外的信息;同时,sigaction能够设置进程的掩码,并且能够阻塞进程。

sigqueue函数只要针对实时信号,并且支持传递的信号附带参数,常常和sigaction函数配合使用。

sigaction.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
void fun(int sig)
{
	if(sig == SIGUSR1)
	  printf("Received SIGUSR1!\n");
}

int main()
{
	printf("This is the receive process!\n");
	printf("The process pid is: %d\n",getpid());

	struct sigaction act,oldact;

	act.sa_handler = fun;
	act.sa_flags = 0;

	sigaction(SIGUSR1,&act,&oldact);

	pause();
	return 0;
}

sigaction.c的操作方式与之前相似。

程序运行结果:

sigqueue.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
void handler(int sig,siginfo_t* p,void* q)
{
	if(sig == SIGUSR1)
	  printf("Received SIGUSR1!\n");
}

int main()
{
	union sigval mysigval;
	struct sigaction act;

	int pid;
	pid = fork();

	if(pid < 0)
		perror("fork");
	else if(pid == 0)
	{
		printf("This is the received process!\n");
        act.sa_sigaction = handler;
        act.sa_flags = SA_SIGINFO;

		if(sigaction(SIGUSR1,&act,NULL) < 0)
			perror("sigaction");

		while(1);
	}
	else
	{
		printf("This is the send process!\n");
		sleep(1);
		if(sigqueue(pid,SIGUSR1,mysigval) < 0)
		  perror("sigqueue");
	}
	return 0;
}

运行结果如下:

猜你喜欢

转载自blog.csdn.net/Wangguang_/article/details/84948221
今日推荐