进程间的通信(六)

编写程序完成下列要求:

进程A向进程B发送信号,该信号的附带信息为一个字符串“Hello world”;

进程B完成接收信号的功能,并且打印出信号名称以及随着信号一起发送过来的字符串值。

和上一个实验类似,发送进程利用sigqueue函数能够将更多的信息发送给接受进程。

程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handler(int sig,siginfo_t* info,void *p)
{
	printf("The str is: %s\n",info->si_value.sival_ptr);
}

int main()
{
	int pid;
	struct sigaction act;
	act.sa_sigaction = handler;
	act.sa_flags = SA_SIGINFO;

	pid = fork();
	if(pid < 0)
	  perror("fork");
	else if(pid == 0)
	{
		printf("This is the receive process!\n");
		if(sigaction(SIGUSR1,&act,NULL) < 0)
		  perror("sigaction");

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

程序运行结果:

猜你喜欢

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