- //
- // File: writepipe.h
- // Author: root
- //
- // Created on February 19, 2008, 8:51 AM
- //
- #ifndef _WRITEPIPE_H
- #define _WRITEPIPE_H
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <string>
- using namespace std;
- class writepipe{
- private:
- string _wpname;
- int _e;
- int _wpfd;
- bool _block;
- public:
- int gete(){
- return _e;
- }
- int wpwrite(char *buffer,int size);
- int wpwrite(const string& buffer);
- writepipe(const string& name,bool isblock);
- ~writepipe();
- };
- #endif /* _WRITEPIPE_H */
writepipe实现文件:
- #include "writepipe.h"
- writepipe::writepipe(const string& name,bool isblock){
- //
- _wpname = name;
- _block = isblock;
- unlink(_wpname.c_str());
- int _rt = mkfifo(_wpname.c_str(),O_CREAT|O_EXCL);
- if(_rt < 0 && errno == EEXIST){
- //
- _e = errno;
- unlink(_wpname.c_str());
- _rt = mkfifo(_wpname.c_str(),O_CREAT|O_EXCL);
- //goto check;
- }
- if(_block == false){
- _wpfd = open(_wpname.c_str(),O_WRONLY|O_NONBLOCK,0);
- /*
- if(_wpfd != 0){
- _e = errno;
- close(_wpfd);
- _wpfd = -1;
- }
- */
- }else{
- _wpfd = open(_wpname.c_str(),O_WRONLY,0);
- /*
- if(_wpfd != 0){
- _e = errno;
- close(_wpfd);
- _wpfd = -1;
- }
- */
- }
- }
- int writepipe::wpwrite(char *buffer,int size){
- //
- if(_wpfd == -1){
- return -1;
- }else{
- int _rn = 0;
- _rn=write(_wpfd,buffer,size);
- //printf("buffer is %s \n",buffer);
- if(_rn==-1)
- {
- _e = errno;
- }
- return _rn;
- }
- }
- int writepipe::wpwrite(const string& buffer){
- //
- if(_wpfd == -1){
- return -1;
- }else{
- int _rn = 0;
- int sz = buffer.length();
- char *tmp = new char[sz + 1];
- bzero(tmp,sz +1);
- memcpy(tmp,buffer.c_str(),sz);
- _rn=write(_wpfd,tmp,sz);
- delete tmp;
- tmp = NULL;
- if(_rn==-1)
- {
- _e = errno;
- }
- return _rn;
- }
- }
- writepipe::~writepipe(){
- //
- close(_wpfd);
- _wpfd = -1;
- }
测试代码:
- //
- // File: maintest.cc
- // Author: root
- //
- // Created on February 18, 2008, 5:37 PM
- //
- #include <stdlib.h>
- #include <stdio.h>
- #include <string>
- #include <iostream>
- #include <unistd.h>
- //#include "readpipe.h"
- #include "writepipe.h"
- using namespace std;
- int main(int argc, char** argv) {
- writepipe *_p = new writepipe("/tmp/TESTRP",true);
- int i = 0;
- while(i < 10){
- char *b = "r u ok?";
- _p->wpwrite(b,strlen(b));
- i++;
- printf("i is %d", i);
- sleep(1);
- }
- delete _p;
- return (EXIT_SUCCESS);
- }

