⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 a_popen.cpp

📁 一个不错
💻 CPP
字号:
/* Copyright is licensed under GNU LGPL.                 by I.J.Wang 2006   Simulate popen   Build: make a_popen  (g++ a_popen.cpp -pthread -lwy)*/#include "../src/wy_uty.h"#include "../src/wyfifofile.h"#include <sys/types.h>          // fork#include <unistd.h>             // fork// Create a pipe and a process running command loaded by shell, reset// ff to the read or write end of the pipe according to type.// Functionality should be similar to ::popen//static WyRet a_popen(WyFifoFile& ff, const char* command, const char* type){ WyRet r; pid_t child_pid; WyFifoFile tmpff; // check (expect) the argument points to exactly one character string if(type==NULL) {   WY_RETURN( Wym_EFAULT ); } if(::strlen(type)!=1) {   WY_RETURN( Wym_EINVAL); } // Create a pipe by resetting ff/tmpff to the ends of the pipe according // to type(argument) (can also be done by using swap) // switch(type[0]) {   case 'r':            if((r=WyFifoFile::mkpipe(ff,tmpff))!=Ok) {              WY_RETURN(r);            }            break;   case 'w':            if((r=WyFifoFile::mkpipe(tmpff,ff))!=Ok) {              WY_RETURN(r);            }            break;   default:            WY_RETURN( Wym_EINVAL ); }; // fork process child_pid=::fork(); if(child_pid==-1) {   WY_THROW( WyRet() ); } if(child_pid==0) {   // Child process:    //   // Connecting stand input or output to the pipe and   // invoke shell to load and run command(argument)   //   ff.reset();  // reset the unused end   if(type[0]=='r') {     Wy::cout.reset(tmpff);   } else {     Wy::cin.reset(tmpff);   }   ::execl("/bin/sh", "sh", "-c", command, NULL);   WY_RETURN( WyReply(errno) ); } // Parent process:  // // reset the unused end // tmpff.reset(); return(Ok);};int main(void)try { WyRet r; WyFifoFile ff; // popen a pipe and execute command // // Test write // if((r=a_popen(ff, "cat", "w"))!=Ok) {   throw(r); } ff << "Hello, this is written to a_popen\n"; // popen a pipe and execute command // // Test read // if((r=a_popen(ff, "ls -l -S", "r"))!=Ok) {   throw(r); } // construct str of capacity at least 1024 // WyStr str; str._reserve(1024); // loop reading data from ff into str and write to standard output // for(;;) {   ff >> str;   if(str.size()==0) {     break;   }   Wy::cout << str; }; return(0);}catch(const WyRet& e) { if(e!=Ok) {   Wy::cerr << Wy::wrd(e) << '\n'; } return e->c_repcode();}catch(...) { Wy::cerr << "main caught(...)\n"; return(-1);};

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -