版权声明:请多多关注博主哟~ https://blog.csdn.net/qq_37865996/article/details/85565178
题目:设计一个程序,要求创建一个管道,复制进程,父进程往管道中写入字符串“how are you!”,子进程从管道中读取并输入字符串“how are you!”。
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>
int main()
{
pid_t result;
int n;
int pipe_fd[2];
char buf1[100],buf2[100];
memset(buf1,0,sizeof(buf1));
if(pipe(pipe_fd)<0)
{
printf("error!\n");
return -1;
}
result=fork();
if(result<0)
{
printf("error!\n");
exit(0);
}
else if(result==0)
{
close(pipe_fd[1]);
if((n =read(pipe_fd[0],buf1,100))>0)
{
printf("child read %d char,char is %s\n",n,buf1);
close(pipe_fd[0]);
exit(0);
}
}
else
{
close(pipe_fd[0]);
printf("please input pipe word \n");
fgets(buf2,sizeof(buf2),stdin);
if(write(pipe_fd[1],buf2,strlen(buf2))!=-1)
printf("parent write to child is: %s\n",buf2);
close(pipe_fd[1]);
waitpid(result,NULL,0);
exit(0);
}
return 0;
}