LINUX -信号作业-父子进程之间相互通信

  1. 编写一个程序,用SIGUSR1作为父子进程间通信的信号,父进程先向子进程发出信号,子进程收到信号后打印“Son has received the signal!”,然后子进程向父进程也发出一个信号,然后退出;父进程收到信号后,打印“Father has received the signal!”,然后退出。
    第一版本
#include 
#include 
#include 
#include 
#include 
#include 


void signal_handler(int signum,siginfo_t *info,void *ptr)
{
	printf("child have receive father signum = %d and information %d\n",signum,info->si_value.sival_int );

	union sigval tmp1;
	tmp1.sival_int = 101;
	//给进程号发送pid 和 tmp
	printf("child has send info to %d\n",info->si_pid);
	sigqueue(info->si_pid,SIGUSR1,tmp1);
}
void signal_handler1(int signum,siginfo_t *info,void *ptr)
{
	printf("father have receive father signum = %d and information %d\n",signum,info->si_value.sival_int );
	wait(NULL);

}
int main(int argc, char const *argv[])
{
	
		pid_t pid;
		pid = fork();
		if(pid == 0){

		    printf("pid = %d fatherpid = %d\n",getpid(),getppid());
			struct sigaction act , oact;

			//指定信号处理回调函数考虑以下和handler函数的区别
			act.sa_sigaction = signal_handler;
	        //阻塞为空
	        sigemptyset(&act.sa_mask);
	        //指定调用 signal_handler=0?
	        act.sa_flags = SA_SIGINFO;

	        //注册信号
	        sigaction(SIGUSR1, &act, &oact);

			 pause();//捕捉信号

			 //考虑执行程序以后直接从pause 退出呢?还是先执行函数在推行湖呢
			 exit(1);

		}
		else if(pid>0){

			sleep(3);
			union sigval tmp;
			tmp.sival_int = 100;
			//给进程号发送pid 和 tmp
			printf("father has send info to %d\n",pid);
			sigqueue(pid,SIGUSR1,tmp);

			struct sigaction act1 , oact1;

			//指定信号处理回调函数考虑以下和handler函数的区别
			act1.sa_sigaction = signal_handler1;
	        //阻塞为空
	        sigemptyset(&act1.sa_mask);
	        //指定调用 signal_handler=0?
	        act1.sa_flags = SA_SIGINFO;

	        //注册信号
	        sigaction(SIGUSR1, &act1, &oact1);

			pause();//捕捉信号*/
		}
		else
		{
			perror("fork");
			exit(-1);
		}

	return 0;
}

LINUX -信号作业-父子进程之间相互通信_第1张图片


你可能感兴趣的:(Linux,通信,siquenu)