operating system —— Experiment 3 ( Interprocess communication )——3.3.4

Experimental purpose

1, understand linux Basic principle of process communication in system .

2, Analyze the phenomenon of process competition for resources , Learn how to solve process mutual exclusion .

3.3.4 Pipeline communication of processes ( Must do )

Prepare a procedure , Pipeline communication of process . Use system call pipe() Build a pipeline first . Two sub processes p1 And write a sentence to the pipeline respectively :

Child1processissendingamessage!

Child2processissendingamessage!

The parent process reads the information from the two child processes from the pipeline and displays it on the screen .

First step

establish c folder , Create under it hello.c file
mkdir c vim test.c
Step two

Write reference program

program
#include<unistd.h> #include<stdio.h> #include<signal.h> int pid1,pid2; main()
{ int fd[3]; char outpipe[100],inpipe[100]; pipe(fd); while((pid1=fork())==-1);
if(pid1==0) { printf("p1\n"); lockf(fd[1],1,0);
sprintf(outpipe,"child1processissendingamessage!"); write(fd[1],outpipe,50);
sleep(1); lockf(fd[1],0,0); exit(0); } else { while((pid2=fork())==-1);
if(pid2==0) { printf("p2\n"); lockf(fd[1],1,0);
sprintf(outpipe,"child2processissendingamessage!"); write(fd[1],outpipe,50);
sleep(1); lockf(fd[1],0,0); exit(0); } else { printf("parent\n");
wait(0);/* synchronization */ read(fd[0],inpipe,50);/* Read length from pipe as 50 Byte string */ printf("%s\n",inpipe);
wait(0); read(fd[0],inpipe,50); printf("%s\n",inpipe); exit(0); } } }
result

Relevant knowledge

Unnamed Pipes ( pipe ): Pipeline is a half duplex communication mode , Data can only flow in one direction , And can only be used between processes with kinship . The kinship of process usually refers to the parent-child process relationship .

Famous pipeline (namedpipe): The well-known pipeline is also a half duplex communication mode , But it allows communication between unrelated processes .

Characteristics of pipeline communication : Pipes can only carry unformatted byte streams .

In the observation procedure sleep(1) What does it do ?

answer : Lengthen the time that the subprocess occupies the pipeline , No child process 1 Output first and child process 2 Function of rear output .

Subprocess 1 and 2 Why can the pipeline be operated ?

answer : Because pipe The pipeline belongs to nameless pipeline , call pipe() This file descriptor is recognized by the parent process and its descendants , Can use this file ( The Conduit ) Communicate .

( From the experimental report )

Technology