Experimental four-pipe communication of Linux operating system experiment series

1. The purpose of the experiment
1. To understand what a pipe is
2. To be familiar with the pipe communication method supported by UNIX/LINUX

2. Experiment content:
Write a program to realize the pipeline communication of the process. Use the system call pipe() to establish a pipe, and the two child processes P1 and P2 each write a sentence to the pipe:
Child 1 is sending a message!
Child 2 is sending a message! The
parent process reads two from the child process from the pipe Information and display.

Three, the experimental environment

Linux operating system

4. Experimental process and running results
Source code:
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
int pid1,pid2;
int main()
{ int fd [2]; char outpipe[100],inpipe[100]; pipe(fd);/ create a pipe / while((pid1=fork())



-1);
if(pid1
0)
{
lockf(fd[1],1,0);
sprintf(outpipe,“child 1 process is sending message!”);
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 2 process is sending message!”);
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);
}
}
}

Result graph:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43372169/article/details/110521578