read
#include<unistd.h>
ssize_t read(int fd,void *buff,size_t bytes)
在unix下,read函数从打开文件中读取数据。今天在使用管道在父子进程之间进行信息交互时,对管道的read操作总不符合预期。我们都知道在对文件(如txt)进行读取时,文件末尾会自动补一个文件尾标志,即EOF,所以read返回值:返回读取的字节数,若已到文件尾,则返回0。但是对于管道来说,并不会给你添加额外的信息。所以对于管道进行read时,只有当管道非空时,read才会返回,或者父进程退出。
代码如下
2 #include"iostream"
3 #include<stdlib.h>
4 #include<cstring>
5 #include<unistd.h>
6 #include<sys/wait.h>
7 using namespace std;
8 int main(int argc,char *argv[])
9 {
10 int fd[2];
11 int n;
12 pid_t pid;
13 pipe(fd);
14 char buff[64];
19 pid=fork();
20 if(pid== 0)
21 {
22 //child process
23 close(fd[1]);
24 cout<<"child process"<< endl;
32 n=read(fd[0],