目录
目录
一、实验内容
利用信号通信机制在父子进程及兄弟进程间进行通信。
父进程创建一个有名事件,由子进程发送事件信号,父进程获取事件信号后进行相应的处理。
二、实验环境
Linux操作系统
三、相关知识
1.进程通信
各个进程交换信息的过程就是进程通信的过程。进程通信可分为低级通信和高级通信,直接通信和间接通信。
(1)、低级通信和高级通信
①低级通信:只能传递状态和整数值(控制信息),包括实现进程互斥和同步所采用的信号量和管程机制都属于这种方式。
②高级通信:能够传送大批量数据。
(2)、直接通信和间接通信
①直接通信:信息由发送方直接传递给接收方。
②间接通信:将收发双方进程之外的共享数及结构作为通信中转,实现通信,如消息队列。
2.相关Linux函数
(1)、signal()函数:设置某一信号对应动作。
头文件:#include <signal.h>
函数原型:sighandler_t signal(int signum,sighandler_t handler);
第一个参数:signum:指明了要处理的信号的类型。
第二个参数:handler:描述了与信号关联的动作。
返回值:返回先前的信号处理函数指针,若有错误返回SIG_ERR(-1)。
常见信号:SIGINT:终止进程 SIGKILL:kill信号 SIGUSR1:用户自定义信号1。
(2)、信号发送函数:kill()
头文件:#include <signal.h>
#include <sys/types.h>
函数原型:int kill(pid_t pid,int signo);
参数说明:pid:接收信号的进程的进程号。
Signo:发送的信号值。
四、源代码
#include <unistd.h>
#include <signal.h>
#include <wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
void sigchld_handler(int sig){
printf("pid here is %d\n",getpid());
printf("process recived a signal sucessfully\n");
}
void main(){
pid_t id=fork();//create child process
if(id==0){
//child process
printf("I am child process.My pid is %d\n",getpid());
kill(getppid(),SIGUSR2);//child process send the signal to parent signal
sleep(1);
exit(1);
}
else if(id>0){
//parent process
signal(SIGUSR2, sigchld_handler);//set the signal
waitpid(id,NULL,0);//wait child process
printf("I am parent process,my pid is %d\n",getpid());
}
else{
printf("fork error!\n");
exit(1);
}
}