实验目的:
了解管道通信机制的基本原理
掌握父子进程使用无名管道通讯的方法
实验内容:
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<string.h>
int main(){
int fd[2], pid, n;
char outpipe[50], inpipe[50];
memset(outpipe, 0 ,sizeof(outpipe));
memset(inpipe, 0, sizeof(inpipe));
pipe(fd);
pid = fork();
if(pid == 0){
sprintf(outpipe, "I am child process");
lockf(fd[1], 1, 0);//枷锁
write(fd[1], outpipe, strlen(outpipe));
lockf(fd[1], 0, 0);//解说
printf("child process write %d bytes : %s\n", strlen(outpipe), outpipe);
}else{
wait(0);
lockf(fd[0], 1, 0);
n = read(fd[0], inpipe, 25);
lockf(fd[0], 0, 0);
printf("parent process %d read %d bytes: %s\n", getpid(), n, inpipe);
}
}
有名管道和无名管道的不同之处
无名管道只允许由血缘关系的进程之间的通讯
有名管道可以让没有w个进程之间进行通讯
同一进程树的兄弟进程通信程序
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<string.h>
int mian() {
int fd[2], pid, pir, n, i;
char send[50] = "b", receive[50] = "b";
pipe(fd);
pid = fork();
if(pid == 0){
while(send[0] != 'a'){
printf("Child1 inputs information from keyboard:\n");
scanf("%s", send);
lockf(fd[1], 1, 0);
write(fd[1], send, strlen(send));
lockf(fd[1], 0, 0);
printf("Send :%s\n", send);
sleep(1);
}
}else{
pir = fork();
if(pir == 0){
while(receive[0] != 'a'){
lockf(fd[0], 1, 0);
n = read(fd[0], receive, 20);
lockf(fd[0], 0, 0);
printf("Child2 received :%s\n", receive);
}
}else{
wait(0);
wait(0);
printf("parent is kill!\n");
}
}
}