实验目的
按要求编写2个C语言程序。
程序1
编制实现软中断通信的程序。父进程fork两个子进程。等待一段时间后,kill子进程形成软中断,并wait函数等待子进程退出信号。
程序1流程图
运行程序soft_ipc,直到输入ctrl+\,产生如下的输出,其中进程的PID和顺序可以不同,但其他输出内容必须一致。
程序2
编制实现进程的管道通信的程序。父进程开通pipe,并fork两个子进程。接收来自于子进程的信息并输出在Shell里。
程序2流程图
运行pipe_ipc,输出如下所示内容。(注:子进程1和2的输出顺序可以不同。)
实验过程
exp02_1.c
#include
#include
#include
#include
#include
int wait_flag;
void stop();
int main(void){
int pid1, pid2, pid3;
signal(3, stop);
printf("Register a signal handler for signal 3.\n");
while((pid1 = fork()) == -1); //创建子进程1
if(pid1 > 0) //是父进程
{
printf("Process %d got a signal.\n", pid1);
while((pid2 = fork()) == -1); //创建子进程2
if(pid2 > 0) //是父进程
{
printf("Process %d got a signal.\n", pid2);
wait_flag = 1;
sleep(5);
kill(pid1, 16);
kill(pid2, 17);
wait(0);
printf("Parent processs exit normally!\n");
}
else //是子进程2
{
wait_flag = 1;
signal(17, stop);
printf("Child process 2 is killed by parent !!\n"); //打印信息
while((pid3 = fork()) == -1);
if(pid3 > 0){
printf("Precess %d got a signal.\n", pid3);
}
}
}
else //是子进程1
{
wait_flag = 1;
signal(16, stop);
printf("Child process 1 is killed by parent !!\n"); //打印信息
}
return 0;
}
void stop()
{
wait_flag = 0;
}
exp02_2.c
#include
#include
#include
#include
#include
int pid1, pid2;
int main(void) {
int fd[2];
char OutPipe[100], InPipe[100];
pipe(fd);
while ((pid1 = fork()) == -1);
if (pid1 == 0) {
lockf(fd[1], 1, 0);
sprintf(OutPipe, "Child process 1 is sending message!\n");
write(fd[1], OutPipe, 50);
sleep(5);
lockf(fd[1], 0, 0);
exit(0);
}
else {
while ((pid2 = fork()) == -1);
if (pid2 == 0) {
lockf(fd[1], 1, 0);
sprintf(OutPipe, "Child process 2 is sending message!\n");
write(fd[1], OutPipe, 50);
sleep(5);
lockf(fd[1], 0, 0);
exit(0);
}
else {
wait(0);
read(fd[0], InPipe, 50);
printf("%s\n", InPipe);
wait(0);
read(fd[0], InPipe, 50);
printf("%s\n", InPipe);
exit(0);
}
}
}
实验结果
程序1运行结果
程序2运行结果
原文:https://www.cnblogs.com/ast935478677/p/14125442.html