实验7多进程间的通信案例.doc
文本预览下载声明
实验
实验目的:
实验要求:
熟练使用该节所介绍
实验器材:
软件:
1.安装了的vmware虚拟机
硬件:PC机一台
实验步骤:
#include stdio.h
#include unistd.h
#includesignal.h
void f(int sig)
{
printf(catch signal %d\n,sig);
}
int main()
{
int i=0;
signal(SIGINT,f);
printf(pid=%d\n,getpid());
while(1)
{
printf(%d\n,i++);
sleep(1);
}
return 0;
}
编写一段程序,使用系统调用函数fork( )创建两个子进程,再用系统调用函数
signal( )让父进程捕捉信号SIGINT(可以键入ctrl+c 来触发,也可以用kill 命令来
触发),当捕捉到中断信号后,父进程用系统调用函数kill( )向两个子进程发出信
号,子进程捕捉到父进程发来的信号后,分别输出下列信息后终止:
Child process 1 is killed by parent!
Child process 2 is killed by parent!
参考代码如下:
#include myhead.h
void f(int sig)
{
kill(p1, SIGUSR1);
kill(p2, SIGUSR2);
}
void f1(int sig)
{
printf(p1 catch the signal: %d\n, sig);
}
void f2(int sig)
{
printf(p2 catch the signal: %d\n, sig);
}
int main(void)
{
pid_t p1, p2;
p1 = fork();
if(p1 0)
{
p2 = fork();
if(p2 0) // parent
{
// 告诉内核,以后如果SIGINT来了,就去执行函数f
signal(SIGINT, f);
pause();
}
else if(p2 == 0) // child 2
{
signal(SIGUSR2, f2);
pause();
}
}
else if(p1 == 0) // child 1
{
signal(SIGUSR1, f1);
pause();
}
return 0;
}
用共享内存和信号量实现两个进程间的通信,一个写进程jack.c,向共享内存中写入数据,一个读进程rose.c从共享内存中读取数据。
jack.c的参考代码如下:
#include stdio.h
#include errno.h
#include fcntl.h
#include sys/types.h
#include sys/ipc.h
#include sys/shm.h
#include strings.h
#include sys/stat.h
#include semaphore.h
#define BUFSZ 1024
int main(void)
{
key_t key = ftok(., 1);
int shmid = shmget(key, BUFSZ, 0666|IPC_CREAT|IPC_EXCL);
if(shmid == -1 errno == EEXIST)
{
shmid = shmget(key, BUFSZ, 0666);
}
char *shmaddr = shmat(shmid, NULL, 0);
bzero(shmaddr, BUFSZ);
fgets(shmaddr, BUFSZ, stdin);
sem_t *s = sem_open(/mysem, O_CREAT|O_EXCL, 0666, 0);
if(s == SEM_FAILED errno == EEXIST)
{
s = sem_open(/mysem, 0);
}
sem_post(s);
return 0;
}
rose.c的参考代码如下:
#include stdio.h
#include fcntl.h
#include sys/types.h
#include sys/shm.h
#include sys/ipc.h
#include sys/stat.h
#include errno.h
#include semaphore.h
#define BUFSZ 1024
int main(void)
{
key_t key = ftok(.
显示全部