LINUX -信號作業-父子進程之間相互通信

  1. 編寫一個程序,用SIGUSR1作爲父子進程間通信的信號,父進程先向子進程發出信號,子進程收到信號後打印“Son has received the signal!”,然後子進程向父進程也發出一個信號,然後退出;父進程收到信號後,打印“Father has received the signal!”,然後退出。
    第一版本
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>


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;
}

在這裏插入圖片描述


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章