#include<string.h>
#include<stdio.h>
#include<fcntl.h>
#include<wait.h>
#include<unistd.h>
#include<stdlib.h>
#define MAX_LINE 80
int main()
{
int fd[2];
int ret=pipe(fd);
if(ret==-1)
{
printf("error in creat pipe\n");
}
else if(ret==0)
{
int pid=fork();
if(pid==-1)
{
printf("error in fork\n");
}
else if(pid==0) //child
{
close(fd[1]); //close write
sleep(5);
char* buf1=(char*)malloc(sizeof(char)*MAX_LINE);
int n1=read(fd[0],buf1,MAX_LINE);
printf("read data from pipe: %d bits\n",n1);
puts(buf1);
close(fd[0]);
printf("child is finished\n");
printf("\n");
}
else //parent
{
close(fd[0]); //close read
char* buf2="Hello world";
int n2=write(fd[1],buf2,strlen(buf2));
printf("write data: %d\n",n2);
puts(buf2);
close(fd[1]); //close write
sleep(5);
printf("parent is finished\n");
printf("\n");
}
}
return 0;
}
Linux 西电操作系统上机4
于 2023-05-11 18:19:26 首次发布