管道是有pipe函数创建。
int pipe(int fileds[2]);
通常不会为来数据通信而在单个进程内使用管道,而是在父子进程中建立管道传递数据,下面例子:建立一条从父进程到子进程到管道,需要在父进程中关闭管道到读端(pipe[0]),在子进程中关闭管道到的写端(pipe[1]).
#include
#include
#include
#include
#include
int main(int argc,char **argv)
{
static const char mesg[]="hello world";
char buf[BUFSIZ];
size_t rcount,wcount;
int pipefd[2];
size_t la;
pid_t pid;
if(pipe(pipefd)<0)
fprintf(stderr,"%s:pipe failed:%s\n",argv[0],strerror(errno));
exit(1);
if((pid=fork())<0)
perror("fork error");
else if(pid>0)
{
printf("PIPE(parent):read end = fd %d,write end = fd %d\n",pipefd[0],pipefd[1]);
close(pipefd[0]);
la=strlen(mesg);
if((wcount=write(pipefd[1],mesg,la))!=la)
fprintf(stderr,"%s:write failed:%s\n",argv[0],strerror(errno));
exit(1);
printf("write <%s> via pipe\n",mesg);
close(pipefd[1]);
}else{
printf("PIPE(child):read end=fd %d,write end=fd %d\n",pipefd[0],pipefd[1]);
close(pipefd[1]);
rcount=read(pipefd[0],buf,BUFSIZ);
buf[rcount]='\0';
printf("read<%s>from pipe\n",buf);
close(pipefd[0]);
}
exit(0);
}
程序没有运行出结果,还得好好弄一下。
FILE *popen(const char *command,const char *type)
int pclose(FILE *fp)
popen函数参数command为popen函数要执行到到命令,指向一个以NULL 结束符结尾到字符串。type有两个取值:r和w。返回值:若成功返回文件指针,出错返回NULL。
pclose函数返回值:cmdstring的终止状态,出错返回-1.
FIFO创建:mkfifo()函数
#include
#inlcude
int mkfifo(const char *pathname,mode_t mode)
pathname:一个普通的路径名。
mode:O_RDONLY:读管道
O_WRONLY:写管道
O_RDWR:读写管道
O_NONBLOCK:非阻塞管道
O_CREAT:如果该文件不存在,就创建一个新的文件
O_EXCL:如果配合O_CREAT时文件存在,那么返回错误信息。
#include
#include
#include
#include
#include
#include
#include
#include
#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1021*1021*10)
int main()
{
int pipe_fd;
int res;
int open_mode=O_WRONLY;
int bytes_sent=0;
char buffer[BUFFER_SIZE+1];
if(access(FIFO_NAME,F_OK)==-1){
res=mkfifo(FIFO_NAME,0777);
if(res!=0){
fprintf(stderr,"could not creat fifo %s\n",FIFO_NAME);
return 1;
}
}
printf("process %d opening FIFO O_WRONLY\n",getpid());
pipe_fd=open(FIFO_NAME,open_mode);
printf("process %d result %d\n",getpid(),pipe_fd);
if(pipe_fd!=-1){
while(bytes_sent
res=write(pipe_fd,buffer,BUFFER_SIZE);
if(res==-1)
{
fprintf(stderr,"write error on pipe\n");
return 1;
}
bytes_sent==res;
}
(void)close(pipe_fd);
}
else
{
return 1;
}
printf("process %d finished\n",getpid());
return 0;
}
产生数据
#include
#include
#include
#include
#include
#include
#include
#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF
int main()
{
int pipe_fd;
int res;
int open_mode=O_RDONLY;
char buffer[BUFFER_SIZE+1];
int bytes_read=0;
memset(buffer,'\0',sizeof(buffer));
printf("process %d opening FIFO O_RDONLY\n",getpid());
pipe_fd=open(FIFO_NAME,open_mode);
printf("process %d result %d\n",getpid(),pipe_fd);
if(pipe_fd!=-1)
{
do
{
res=read(pipe_fd,buffer,BUFFER_SIZE);
bytes_read+=res;
}while(res>0);
close(pipe_fd);
}
else{
return 0;
}
printf("process %d finished %d bytes read\n",getpid(),bytes_read);
return 1;
}
接收数据
阅读(855) | 评论(0) | 转发(0) |