进程间的通信(四)

编写程序完成以下要求:

进程A向进程B发送信号;
进程B收到进程A发送的信号后,打印出发送信号进程的pid,uid以及信号值。

通过对之前实验的了解,我们知道sigqueue函数能够向进程发送除信号之外的其它更多的信息。因此,我决定应用四个queue函数将发送进程的pid,uid跟信号一起发送给接受进程。

程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
void handler(int sig,siginfo_t* act,void *p)
{
	printf("The sender's pid is: %d\n",act->si_pid);
	printf("The sender's uid is: %d\n",act->si_uid);
	printf("The sig is: %d\n",sig);
}

int main()
{
	int pid;
	union sigval mysigval;
	pid = fork();
	if(pid < 0)
	  perror("fork");
	else if(pid == 0)
	{
		printf("This is the received process!\n");
		struct sigaction act;
		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);
		printf("The sender's pid is: %d\n",getpid());
		if(sigqueue(pid,SIGUSR1,mysigval) < 0)
		  perror("sigqueue");
	}
	return 0;
}

程序运行结果:

猜你喜欢

转载自blog.csdn.net/Wangguang_/article/details/84963056