进程间管道通信
//start from the very beginning,and to create greatness
//@author: Chuangwei Lin
//@E-mail:979951191@qq.com
//@brief: 一个进程间管道通信的例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char const *argv[])
{
int result = -1;//创建管道结果
int fd[2],nbytes;//文件描述符和字符个数
pid_t pid;//进程pid值
char string[] = "进程间管道通信";
char readbuffer[80];//字符缓冲区
//文件符1用于写,0用于读
int* write_fd = &fd[1];
int* read_fd = &fd[0];
result = pipe(fd);//建立管道
if(-1 == result)
{
printf("管道建立失败\n");
return -1;
}
pid = fork();//分叉进程
if (-1 == pid)
{
printf("fork进程失败\n");
return -1;
}
if (0 == pid)//子进程
{
close(*read_fd);//关闭读端
result = write(*write_fd,string,strlen(string));//向管道段写入字符
return 0;
}
else//父进程
{
close(*write_fd);//关闭写端
nbytes = read(*read_fd,readbuffer, sizeof(readbuffer));//从管道读数据
printf("接收到%d个数据,内容为:%s\n",nbytes,readbuffer);
}
return 0;
}
运行结果为:
[root@localhost lcw20150805]# ./lcw_pipe
接收到21个数据,内容为:进程间管道通信