int filedes[2];
pipe(filedes);//这样这个含有两个元素的int型数组就变成了管道
无名管道只能用于父子进程间的通信
filedes[1]用于向管道中写入数据
filedes[2]用于从管道中读出数据
经过验证子进程写父进程读以及父进程写子进程读都可以:管道通信属于半双工通信,两边都可以发送和接受,但不可以同时发送和接受
/*子进程写父进程读*/
pipe(filedes);//这样这个含有两个元素的int型数组就变成了管道
无名管道只能用于父子进程间的通信
filedes[1]用于向管道中写入数据
filedes[2]用于从管道中读出数据
ssize_t read(int fd,void *buf/*buf所指向的那一块区域*/ size_t count/*fd所指向的文件传送count个字节到buf中*/)
注:必须在fork之前调用pipe()否则子进程将不会集成文件描述符
例子如下
#include<stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int filedes[2];
char buffer[80];
pipe(filedes);
if(fork()>0)/*父进程*/
{
char s[]="hello!\n";
write(filedes[1],s,sizeof(s));/*将s中的内容写入到管道中*/
exit(0);
}
else/*子进程*/
{
read(filedes[0],buffer,80);/*读出管道中的内容,放到buffer中*/
printf("%s",buffer);
}
return 0;
}
例子2
经过验证子进程写父进程读以及父进程写子进程读都可以:管道通信属于半双工通信,两边都可以发送和接受,但不可以同时发送和接受
/*子进程写父进程读*/
#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main(int argc, char **argv)
{
int pipe_fd[2];
pid_t pid;
char r_buf[100];
char w_buf[4];
char *p_wbuf;
int r_num;
int cmd;
memset(r_buf,0,sizeof(r_buf));/*r_buf为首地址的后面的长度为sizeof(r_buf)的内存清零*/
memset(w_buf,0,sizeof(w_buf));/*将首地址为w_buf的后面长度为sizeof(w_buf)的内存清零*/
// p_wbuf=w_buf;
if(pipe(pipe_fd)<0)
{
printf("pipe create error\n");
return -1;
}
if((pid=fork())==0)
{
printf("\n");
close(pipe_fd[1]);/*在子进程中关掉写管道*/
sleep(3);
r_num=read(pipe_fd[0],r_buf,100);
printf("read num is %d the data read from the pipe is %d\n",r_num,atoi(r_buf));/*字符转换*/
close(pipe_fd[0]);/*读取数据后关掉读管道*/
exit(0);
}
else if(pid>0)
{
close (pipe_fd[0]);/*在父进程中关掉读管道*/
strcpy(w_buf,"150");
if(write(pipe_fd[1],w_buf,4)!=-1)
{
printf("parent write over\n");
}
close(pipe_fd[1]);/*写入数据后关闭关掉写管道*/
printf("parent close pipe_fd[1] over\n");
sleep(5);
}
return 0;
}
父进程写子进程读
#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main(int argc, char **argv)
{
int pipe_fd[2];
pid_t pid;
char r_buf[100];
char w_buf[4];
char *p_wbuf;
int r_num;
int cmd;
memset(r_buf,0,sizeof(r_buf));/*r_buf为首地址的后面的长度为sizeof(r_buf)的内存清零*/
memset(w_buf,0,sizeof(w_buf));/*将首地址为w_buf的后面长度为sizeof(w_buf)的内存清零*/
// p_wbuf=w_buf;
if(pipe(pipe_fd)<0)
{
printf("pipe create error\n");
return -1;
}
if((pid=fork())>0)
{
printf("\n");
//close(pipe_fd[1]);/*关掉写管道*/
sleep(3);
r_num=read(pipe_fd[0],r_buf,100);
printf("read num is %d the data read from the pipe is %d\n",r_num,atoi(r_buf));/*字符转换*/
close(pipe_fd[0]);/*关掉读管道*/
exit(0);
}
else if(pid==0)
{
//close (pipe_fd[0]);/*关掉读管道*/
strcpy(w_buf,"150");
if(write(pipe_fd[1],w_buf,4)!=-1)
{
printf("parent write over\n");
}
close(pipe_fd[1]);/*关掉写管道*/
printf("parent close pipe_fd[1] over\n");
sleep(5);
}
return 0;
}