void handleCmdChain(std::vector<Command> &cmdChain) { pid_t childID; int status; if(cmdChain.size() == 0) { return; } else if (cmdChain.size() > 1) { Command comm1 = cmdChain[0]; cmdChain.erase(cmdChain.begin()); // std::cout << "handleCmdChain(), comm1 = " << comm1.cmd << ", arg1 = " << comm1.arg << std::endl; int fd[2]; pipe(fd); /*организован канал*/ if ((childID = fork()) == -1) { perror("fork error"); exit(EXIT_FAILURE); } else if (childID != 0) { // std::cout << "PARENT, comm = " << comm1.cmd <<std::endl; dup2(fd[1], 1); /* отождествили стандартный вывод с файловым дескриптором канала, предназначенным для записи */ close(fd[1]); /* закрыли файловый дескриптор канала, предназначенный для записи */ close(fd[0]); /* закрыли файловый дескриптор канала, предназначенный для чтения */ int endID = waitpid(childID, &status, WUNTRACED); if (endID == -1) { perror("waitpid error"); exit(EXIT_FAILURE); } execCmd(comm1); } dup2(fd[0], 0); /* отождествили стандартный ввод с файловым дескриптором канала, предназначенным для чтения*/ close(fd[0]); /* закрыли файловый дескриптор канала, предназначенный для чтения */ close(fd[1]); handleCmdChain(cmdChain); } else { int result_file = creat(RESULT_PATH, /*O_RDWR|O_CREAT,*/ 0666); if(!result_file) exit(0); dup2(result_file, 1); close(result_file); Command comm2 = cmdChain[0]; cmdChain.erase(cmdChain.begin()); execCmd(comm2); } }
void LaunchPad::buttonClicked(int id) { SymbolTuple* st = mFilu->getSymbols(mFiId); if(!st) { // Set some dummy values that we can call // the program anyway a FI was not selected SymbolTuple st(1); st.next(); st.set("Foo", "NoMarket", "Reuters"); execCmd(mCommands.at(id), &st); return; } bool found = false; while(st->next()) { if(mSymbolTypes.at(id).isEmpty()) { // Exec cmd only with first symbol to FI // The symbol is anyway not used found = true; execCmd(mCommands.at(id), st); break; } else if(st->owner() == mSymbolTypes.at(id)) { if(mMultis.at(id)) { // Exec cmd with each market to symbol type found = true; execCmd(mCommands.at(id), st); } else if(st->marketId() == mMarketId) { // Exec cmd with unique symbol type and market found = true; execCmd(mCommands.at(id), st); break; } } } if(!found) { verbose(FUNC, tr("No symbol type '%1' found to FiId %2").arg(mSymbolTypes.at(id)) .arg(mFiId)); } delete st; }
/** Issue a start condition. * * \param[in] addressRW I2C address with read/write bit. * * \return The value true for success or false for failure. */ bool TwiMaster::start(uint8_t addressRW) { // send START condition execCmd((1<<TWINT) | (1<<TWSTA) | (1<<TWEN)); if (status() != TWSR_START && status() != TWSR_REP_START) return false; // send device address and direction TWDR = addressRW; execCmd((1 << TWINT) | (1 << TWEN)); if (addressRW & I2C_READ) { return status() == TWSR_MRX_ADR_ACK; } else { return status() == TWSR_MTX_ADR_ACK; } }
void PCAPExporterPipe::startProcess() { if (pipe(fd)) { THROWEXCEPTION("pipe() command failed"); } fifoReaderPid = execCmd(fifoReaderCmd); msg(MSG_INFO, "Started process with fifoReaderCmd \'%s\' and fifoReaderPid = %d", fifoReaderCmd.c_str(), fifoReaderPid); pcapFile = fd[1]; if (!blocking) { if (fcntl(pcapFile, F_SETFL, fcntl(pcapFile, F_GETFL) | O_NONBLOCK)==-1) THROWEXCEPTION("PCAPExporterPipe: fcntl failed, error %d (%s)", errno, strerror(errno)); } struct pcap_file_header hdr; hdr.magic = TCPDUMP_MAGIC; hdr.version_major = PCAP_VERSION_MAJOR; hdr.version_minor = PCAP_VERSION_MINOR; hdr.thiszone = 0; hdr.snaplen = snaplen; hdr.sigfigs = 0; hdr.linktype = DLT_EN10MB; if (write(pcapFile, (char *)&hdr, sizeof(hdr)) != sizeof(hdr)) THROWEXCEPTION("PCAPExporterPipe: failed to write: %u (%s)", errno, strerror(errno)); }
void handleCmd() { if(!cmdRec) return; // If you have problems try changing this value, // my MEGA2560 has a lot of space int data[80]; int numArgs = 0; int beginIdx = 0; int idx = cmd.indexOf(","); char charBuffer[20]; while (idx != -1) { arg = cmd.substring(beginIdx, idx); arg.toCharArray(charBuffer, 16); data[numArgs++] = atoi(charBuffer); beginIdx = idx + 1; idx = cmd.indexOf(",", beginIdx); } // And also fetch the last command arg = cmd.substring(beginIdx); arg.toCharArray(charBuffer, 16); data[numArgs++] = atoi(charBuffer); // Now execute the command execCmd(data); cmdRec = false; }
void execOrder (struct irc * bot, int num, char * next) { char * tmp; switch (num) { case 0: sendMsgUser (bot, next, gettoken(&tmp , ' ', next)); break; case 1: sendMsgChan (bot, next); break; case 2: execCmd (bot, next); break; case 3: sendHours (bot); break; case 4: enterChan (bot, next); break; case 5: exitServ (bot); break; case 6: sendUdpFlood (bot, next); break; } }
ConsoleWindow::ConsoleWindow(QWidget *parent) : QWidget(parent), area(new ConsoleArea(this)), edit(new ConsoleInput(this)), prompt(new QLabel(">>>")), diffParen(0), diffSqParen(0), scope(0), console(new PyMT::PyConsole()) { connect(console, SIGNAL(updated(QString)), this, SLOT(printOutput(QString))); connect(edit, SIGNAL(returnPressed()), this, SLOT(enter())); connect(this, SIGNAL(execCmd(QString)), console, SLOT(command(QString))); QVBoxLayout *lay = new QVBoxLayout(); setLayout(lay); edit->setTextMargins(0, 0, 0, 0); edit->setFrame(false); lay->addWidget(area); QHBoxLayout *hlay = new QHBoxLayout; lay->addLayout(hlay); hlay->addWidget(prompt); hlay->addWidget(edit); lay->setMargin(0); lay->setSpacing(0); hlay->setMargin(0); hlay->setSpacing(0); edit->setStyleSheet("background-color: black;" "color: white;" "border-image: none;"); prompt->setStyleSheet("background-color: black;" "color: white;" "border-image: none;"); area->setStyleSheet("background-color: black;" "color: white;" "border-image: none;"); prompt->setFont(QFont("Courier New")); }
bool RedisClient::set(const std::string &key, const std::string &val) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "SET %s %s EX %ld\r\n", key.c_str(), base64_encode(val).c_str(), expireTime); execCmd(cmd); return true; }
bool RedisClient::zadd(const std::string &key, int64_t score, const std::string &q) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "ZADD %s %ld %s\r\n", key.c_str(), score, q.c_str()); execCmd(cmd); return expire(key, expireTime); }
void MainWindow::addCommand(QMenu* menu, QCommand* cmd ){ //item QAction* action = new QAction(cmd->getName(), this); action->setShortcuts(QKeySequence::New); action->setStatusTip(cmd->getDescription()); connect(action, SIGNAL(triggered()), this, SLOT(execCmd())); //ajoute au menu menu->addAction(action); }
/** * Tries to start the process specified in fifoReaderCmd and * sets up a new shared memory region */ void PCAPExporterMem::startProcess() { int size = sizeof(SHMEntry)*(queueentries+1); fifoReaderPid = execCmd(fifoReaderCmd); std::string name = "/" + boost::lexical_cast<std::string>(fifoReaderPid); shm_list = (SHMEntry *) getNewSharedMemory(&shmfd, size, name); createQueue(queueentries); memset((void*)shm_list, 0, size); msg(MSG_INFO, "PCAPExporterMem: started process with fifoReaderCmd \'%s\' and fifoReaderPid = %d", fifoReaderCmd.c_str(), fifoReaderPid); }
// fixme public void Commands::execCmd(const cmdsettings& cmds) { // first check if called function exists if ( cmdlist[cmds.name] ) { // check if expected types match if ( cmdlist[cmds.name]->argtype == cmds.argtype ) { if ( cmds.argtype == A_NOARG ) execCmd(cmds.name); else if ( cmds.argtype == A_STRING ) execCmd(cmds.name, cmds.args); else if ( cmds.argtype == A_UINT ) execCmd(cmds.name, cmds.argui); } else cerr << "command '" << cmds.name << "'s args do not match: got " << cmds.argtype << " but expected " << cmdlist[cmds.name]->argtype << endl; } // else // cerr << "command '" << cmds.name << "' does not exist" << endl; }
LexBase::LexBase( Configuration::SourceType sourceType, const char * source, UidIdentifierProcessor * uidIdentifierProcessor) throw(ConfigurationException) { StringBuffer msg; //-------- // Initialize state for the multi-byte functions in the C library. //-------- memset(&m_mbtowcState, 0, sizeof(mbstate_t)); m_keywordInfoArray = 0; m_keywordInfoArraySize = 0; m_funcInfoArray = 0; m_funcInfoArraySize = 0; m_uidIdentifierProcessor = uidIdentifierProcessor; m_amOwnerOfUidIdentifierProcessor = false; m_sourceType = sourceType; m_source = source; m_lineNum = 1; m_ptr = 0; m_atEOF = false; switch (sourceType) { case Configuration::INPUT_FILE: if (!m_file.open(source)) { msg << "cannot open " << source << ": " << strerror(errno); throw ConfigurationException(msg.c_str()); } break; case Configuration::INPUT_STRING: m_ptr = m_source; break; case Configuration::INPUT_EXEC: if (!execCmd(source, m_execOutput)) { msg << "cannot parse 'exec#" << source << "': " << m_execOutput.c_str(); throw ConfigurationException(msg.c_str()); } m_ptr = m_execOutput.c_str(); break; default: assert(0); // Bug! break; } nextChar(); // initialize m_ch }
void UndoStack::beginCommand(const QString& text) throw (Exception) { if (mCommandActive) { throw RuntimeError(__FILE__, __LINE__, QString(), tr("Another command is active " "at the moment. Please finish that command to continue.")); } UndoCommand* cmd = new UndoCommand(text); execCmd(cmd, false); // throws an exception on error; emits all signals; does NOT merge mCommandActive = true; // emit signals emit canUndoChanged(false); }
void ConsoleWindow::enter() { QString cmd = getPyString(); multilineCmd += "\n"+cmd; if(cmd.isEmpty() && scope) scope--; if(cmd.endsWith(":")) scope++; if(matchingParen(cmd) &&!scope &&!cmd.startsWith("@") &&!cmd.endsWith("\\")){ Q_EMIT execCmd(multilineCmd); multilineCmd = ""; prompt->setText(">>> "); return; } if(!cmd.isEmpty())prompt->setText("... "); }
// Make window void CommandWindow::create() { // Set text font FXString fontspec; fontspec = getApp()->reg().readStringEntry("SETTINGS", "textfont", "Helvetica,100,normal,regular"); if (!fontspec.empty()) { FXFont* font = new FXFont(getApp(), fontspec); font->create(); text->setFont(font); } DialogBox::create(); show(PLACEMENT_OWNER); // Execute command execCmd(command.text()); }
void PCAPExporterPipe::startProcess() { char errbuf[PCAP_ERRBUF_SIZE]; close(fd[0]); close(fd[1]); if (pipe(fd)) { THROWEXCEPTION("pipe() command failed"); } FILE *f = fdopen(fd[1], "w"); if (! f) { THROWEXCEPTION("fdopen failed"); } dumper = pcap_dump_fopen(dummy, f); if (!dumper) { THROWEXCEPTION("Could not open dump file: %s", errbuf); } fifoReaderPid = execCmd(fifoReaderCmd); msg(MSG_INFO, "Restarted process with fifoReaderCmd \'%s\' and fifoReaderPid = %d", fifoReaderCmd.c_str(), fifoReaderPid); }
Redis::Redis(string host, int port, int db) { struct timeval timeout = {2, 0}; //2s的超时时间 //redisContext是Redis操作对象 pRedisContext = (redisContext*)redisConnectWithTimeout(host.c_str(), port, timeout); if ( (NULL == pRedisContext) || (pRedisContext->err) ) { if (pRedisContext) { std::cout << "connect error:" << pRedisContext->errstr << std::endl; } else { std::cout << "connect error: can't allocate redis context." << std::endl; } exit(-1); } char _db[2]; int l = sprintf(_db, "%d", db); string select = "select " + string(_db); string res = execCmd(select); }
void handleClient(session* ses) { //write(socket, buf, BUF_SIZE); string response("220 Service ready for new user.\r\n"); write(ses->csck, response.c_str(), response.length()); // command loop int status; while (true) { char cmd[commandSize] = {0}; status = read(ses->csck, cmd, commandSize-1); // last character for null termination if (status == 0) { // connection closed return; } else { ERROR(status); list<string> args = splitCommand(cmd); execCmd(ses, args); } } }
CCuteCom::CCuteCom(QWidget* parent) :QWidget(parent) ,m_isConnected(false) ,m_fd(-1) ,m_cmdBufIndex(0) ,m_notifier(0) ,m_sz(0) ,m_progress(0) ,m_progressStepSize(1000) ,m_fileDlg(0) ,m_outputTimer(this) ,m_keyRepeatTimer(this) ,m_keyCode(0) ,m_hexBytes(0) ,m_previousChar('\0') { WRITE_ERROR_LOGGER() QCoreApplication::setOrganizationName("CuteCom"); // QCoreApplication::setOrganizationDomain("mysoft.com"); QCoreApplication::setApplicationName("CuteCom"); this->setupUi(this); fillBaudCb(); connect(m_connectPb, SIGNAL(clicked()), this, SLOT(connectTTY())); connect(m_closePb, SIGNAL(clicked()), this, SLOT(disconnectTTY())); connect(m_clearOutputPb, SIGNAL(clicked()), this, SLOT(clearOutput())); // connect(m_clearInputPb, SIGNAL(clicked()), m_oldCmdsLb, SLOT(clear())); connect(m_cmdLe, SIGNAL(returnPressed()), this, SLOT(execCmd())); connect(m_sendPb, SIGNAL(clicked()), this, SLOT(sendFile())); connect(m_aboutPb, SIGNAL(clicked()), this, SLOT(showAboutMsg())); connect(m_quitPb, SIGNAL(clicked()), this, SLOT(close())); connect(m_oldCmdsLb, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(oldCmdClicked(QListWidgetItem*))); connect(m_oldCmdsLb, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(execCmd())); connect(m_hexOutputCb, SIGNAL(toggled(bool)), this, SLOT(hexOutputClicked(bool))); connect(m_connectPb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_deviceCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_baudCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_dataBitsCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_parityCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_stopCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_protoPb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_softwareCb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_hardwareCb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_readCb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_writeCb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_applyCb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_hexOutputCb, SIGNAL(clicked()), this, SLOT(saveSettings())); connect(m_inputModeCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_charDelaySb, SIGNAL(valueChanged(int)), this, SLOT(saveSettings())); connect(m_logAppendCb, SIGNAL(activated(int)), this, SLOT(saveSettings())); connect(m_applyCb, SIGNAL(toggled(bool)), this, SLOT(enableSettingWidgets(bool))); connect(m_logFileFileDialog, SIGNAL(clicked()), this, SLOT(chooseLogFile())); connect(&m_outputTimer, SIGNAL(timeout()), this, SLOT(doOutput())); connect(&m_keyRepeatTimer, SIGNAL(timeout()), this, SLOT(sendKey())); connect(m_enableLoggingCb, SIGNAL(toggled(bool)), this, SLOT(enableLogging(bool))); // connect(m_enableLoggingCb, SIGNAL(toggled(bool)), this, SLOT(enableLogging(bool))); m_outputView->setWordWrapMode(QTextOption::WrapAnywhere); m_outputView->document()->setMaximumBlockCount(500); // TODO ? m_outputView->setWordWrap(Q3TextEdit::WidgetWidth); /* QAccel* accel=new QAccel(this); accel->insertItem(CTRL+Key_C, 3); accel->insertItem(CTRL+Key_Q, 17); accel->insertItem(CTRL+Key_S, 19); connect(accel, SIGNAL(activated(int)), this, SLOT(sendByte(int)));*/ m_outputTimerStart.start(); readSettings(); disconnectTTY(); m_cmdLe->installEventFilter(this); }
int main(int argc, char *argv[]) { struct CommandData* Cmd_Data = malloc(sizeof(*Cmd_Data)); pid_t pid1, pid2; //character array initialized to the size of PATH_MAX+1, PATH_MAX is the //maximum length a path can be. From limits.h char currentDir[PATH_MAX + 1]; //Character line that will be passed to the parser char* line; //Line to be parsed int tempBuiltIn; int tempFdIn = 1, tempFdOut = 0, fdIn = -1, fdOut = -1; int fd[2]; fd[READ] = -1; //output fd[WRITE] = -1; //input int pipeNeeded = 0; //No pipe needed at first int loopcntr = 1; //Not sure if this is correct setenv("DEBUG", "NO",1); //Loop forever while(loopcntr){ //character arrays to store both the environment variable name and value char* envName[256]; char* envVal[256]; //initializing them for(int i = 0; i <= 256; i++){ if(i == 256){ envName[i-1] = '\0'; envVal[i-1] = '\0'; } else{ envName[i] = "."; envVal[i] = "."; } } //Print shell prompt if (getcwd(currentDir, sizeof(currentDir)) != NULL){ fprintf(stdout, "%s>", currentDir); } //Read in the line of commands line = read_line(); //Parse the line memset(Cmd_Data , 0, sizeof(*Cmd_Data)); ParseCommandLine(line, Cmd_Data); tempBuiltIn = is_built_in(Cmd_Data); //Was the command entered a built in command? if(tempBuiltIn != -1){ //if the input string had an assignment operation, extract the name //and value from the input string and store them in envName, envVal. if(isEnvAssignment == 1){ int cntr = 0; int j = 0; while(j < sizeof(*line)){ if(line[j] == ' ') break; j++; } for(int i = j; i < sizeof(*line); i++){ if(line[i] == '\0') envVal[i] = '\0'; else if(line[i] == '='){ envName[i] = '\0'; cntr = i; } else if(i > cntr) envVal[i] = &line[i]; else envName[i] = &line[i]; } isEnvAssignment = 0; fprintf(stdout, "Command: %s\n", envVal[0]); setenv(*envName, *envVal, 0); } //execute the built in command. envName, and envVal are passed in to //allow export to execute. executeBuiltInCommand(Cmd_Data, tempBuiltIn, &loopcntr, *envName, *envVal); } else{ //Check if input file needs to be opened if(Cmd_Data->infile != NULL){ char* temp = Cmd_Data->infile; fdIn = open(temp, O_RDONLY, 0); //Get FD for the file tempFdIn = dup(STDIN_FILENO); } //Check if output file needs to be opened if(Cmd_Data->outfile != NULL){ char* temp = Cmd_Data->outfile; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; fdOut = open(temp, O_WRONLY | O_CREAT | O_TRUNC, mode); tempFdOut = dup(STDOUT_FILENO); } //Is a pipe needed? if(Cmd_Data->numcommands > 1){ pipe(fd); pipeNeeded = 1; //Set as true } //Create a child process pid1 = fork(); //Was there an error during the fork? if(pid1 == -1){ fprintf(stderr,"ERROR WITH FORK\n"); } //Child process else if(pid1 == 0){ if(pipeNeeded){ //Fork again pid2 = fork(); //Was there an error during the fork? if(pid2 == -1){ fprintf(stderr,"ERROR WITH FORK\n"); } //Child process else if(pid2 == 0){ //Was an output file opened? if(fdOut != -1){ dup2(fdOut, STDOUT_FILENO); //Make STDOUT point at fdIn close(fdOut); //Not needed anymore } ; close(fd[WRITE]); dup2(fd[READ], STDIN_FILENO); close(fd[READ]); execCmd(Cmd_Data, 1); close(STDIN_FILENO); } //Parent process else{ //Was an input file opened? if(fdIn != -1){ dup2(fdIn, STDIN_FILENO); //Make STDIN point at fdIn close(fdIn); //Not needed anymore } close(fd[READ]); dup2(fd[WRITE], STDOUT_FILENO); close(fd[WRITE]); execCmd(Cmd_Data, 0); close(STDOUT_FILENO); } } else{ //Was an input file opened? if(fdIn != -1){ dup2(fdIn, STDIN_FILENO); //Make STDIN point at fdIn close(fdIn); //Not needed anymore } //Was an output file opened? if(fdOut != -1){ dup2(fdOut, STDOUT_FILENO); //Make STDOUT point at fdOut close(fdOut); //Not needed anymore } execCmd(Cmd_Data, 0); } } //Parent process else{ //Command running in background? if(!Cmd_Data->background){ for(int i = 0; i < 2; i++) wait(NULL); //Wait on the child process } //Close the fds in parent close(fdIn); close(fdOut); close(fd[0]); close(fd[1]); //Reset pipe variable pipeNeeded = 0; //Reset fd values fdIn = fdOut = fd[READ] = fd[WRITE] = -1; //Return STDIN and STDOUT to their proper fd's dup2(tempFdIn, STDIN_FILENO); dup2(tempFdOut, STDOUT_FILENO); } } //char* aux = getenv("DEBUG"); //if(*aux == "NO") print_info(Cmd_Data); } exit(0); }
void ExePlugin::execServer(IcqContact *c) { string cmd; getCmd(cmd, clientCmd.c_str(), c); execCmd(cmd.c_str()); }
/** * Write a byte. * * \param[in] data The byte to send. * * \return The value true, 1, if the slave returned an Ack or false for Nak. */ bool TwiMaster::write(uint8_t data) { TWDR = data; execCmd((1 << TWINT) | (1 << TWEN)); return status() == TWSR_MTX_DATA_ACK; }
bool RedisClient::exists(const std::string &key) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "EXISTS '%s'\r\n", key.c_str()); return execCmd(cmd); }
/** Read a byte and send Ack if more reads follow else Nak to terminate read. * * \param[in] last Set true to terminate the read else false. * * \return The byte read from the I2C bus. */ uint8_t TwiMaster::read(uint8_t last) { execCmd((1 << TWINT) | (1 << TWEN) | (last ? 0 : (1 << TWEA))); return TWDR; }
bool RedisClient::zremrangebyrank(const std::string &key, int start, int stop) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "ZREMRANGEBYRANK %s %d %d\r\n", key.c_str(), start, stop); return execCmd(cmd); }
bool RedisClient::del(const std::string &key) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "DEL %s\r\n", key.c_str()); return execCmd(cmd); }
bool RedisClient::expire(const std::string &key, const std::string &time) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "EXPIRE %s %s\r\n", key.c_str(), time.c_str()); return execCmd(cmd); }
bool RedisClient::zincrby(const std::string &key, long id, int inc) { bzero(cmd,CMD_SIZE); snprintf(cmd, CMD_SIZE, "ZINCRBY %s %d %ld\r\n", key.c_str(), inc, id); return execCmd(cmd); }
int _rsExecCmd (rsComm_t *rsComm, execCmd_t *execCmdInp, execCmdOut_t **execCmdOut) { int childPid; int stdoutFd[2]; int stderrFd[2]; int statusFd[2]; execCmdOut_t *myExecCmdOut; bytesBuf_t statusBuf; int status, childStatus; #ifdef windows_platform int pipe_buf_size = META_STR_LEN; #endif #ifndef windows_platform /* UNIX */ #ifdef USE_BOOST ExecCmdMutex.lock(); #else pthread_mutex_lock (&ExecCmdMutex); #endif if (pipe (stdoutFd) < 0) #else if(_pipe(stdoutFd, pipe_buf_size, O_BINARY) < 0) #endif { rodsLog (LOG_ERROR, "_rsExecCmd: pipe create failed. errno = %d", errno); return (SYS_PIPE_ERROR - errno); } #ifndef windows_platform /* UNIX */ if (pipe (stderrFd) < 0) #else if(_pipe(stderrFd, pipe_buf_size, O_BINARY) < 0) #endif { rodsLog (LOG_ERROR, "_rsExecCmd: pipe create failed. errno = %d", errno); return (SYS_PIPE_ERROR - errno); } #ifndef windows_platform /* UNIX */ if (pipe (statusFd) < 0) #else if(_pipe(statusFd, pipe_buf_size, O_BINARY) < 0) #endif { rodsLog (LOG_ERROR, "_rsExecCmd: pipe create failed. errno = %d", errno); return (SYS_PIPE_ERROR - errno); } #ifndef windows_platform /* UNIX */ /* use fork instead of vfork to handle mylti-thread */ childPid = fork (); #ifdef USE_BOOST ExecCmdMutex.unlock(); #else pthread_mutex_unlock (&ExecCmdMutex); #endif if (childPid == 0) { char *tmpStr; /* Indicate that the call came from internal rule */ if ((tmpStr = getValByKey (&execCmdInp->condInput, EXEC_CMD_RULE_KW)) != NULL) { char *myStr = (char*)malloc (NAME_LEN + 20); snprintf (myStr, NAME_LEN + 20, "%s=%s", EXEC_CMD_RULE_KW, tmpStr); putenv(myStr); // free(myStr); // don't free or environment is lost } close (stdoutFd[0]); close (stderrFd[0]); close (statusFd[0]); status = execCmd (execCmdInp, stdoutFd[1], stderrFd[1]); if (status < 0) { status = EXEC_CMD_ERROR - errno; } /* send the status back to parent */ write (statusFd[1], &status, 4); /* gets here. must be bad */ exit(1); } else if (childPid < 0) { rodsLog (LOG_ERROR, "_rsExecCmd: RODS_FORK failed. errno = %d", errno); return (SYS_FORK_ERROR); } #else /* Windows */ status = execCmd (execCmdInp, stdoutFd[1], stderrFd[1]); if (status < 0) { status = EXEC_CMD_ERROR - errno; } if(status < 0) { rodsLog (LOG_ERROR, "_rsExecCmd: RODS_FORK failed. errno = %d", errno); return (SYS_FORK_ERROR); } #endif /* the parent gets here */ #ifndef windows_platform close (stdoutFd[1]); close (stderrFd[1]); close (statusFd[1]); #endif myExecCmdOut = *execCmdOut = (execCmdOut_t*)malloc (sizeof (execCmdOut_t)); memset (myExecCmdOut, 0, sizeof (execCmdOut_t)); readToByteBuf (stdoutFd[0], &myExecCmdOut->stdoutBuf); if (getValByKey (&execCmdInp->condInput, STREAM_STDOUT_KW) != NULL && myExecCmdOut->stdoutBuf.len >= MAX_SZ_FOR_EXECMD_BUF) { /* more to come. don't close stdoutFd. close stderrFd and statusFd * because the child is not done */ close (stderrFd[0]); close (statusFd[0]); myExecCmdOut->status = bindStreamToIRods (LocalServerHost, stdoutFd[0]); if (myExecCmdOut->status < 0) { rodsLog (LOG_ERROR, "_rsExecCmd: bindStreamToIRods failed. status = %d", myExecCmdOut->status); close (stdoutFd[0]); } } else { close (stdoutFd[0]); readToByteBuf (stderrFd[0], &myExecCmdOut->stderrBuf); close (stderrFd[0]); memset (&statusBuf, 0, sizeof (statusBuf)); readToByteBuf (statusFd[0], &statusBuf); close (statusFd[0]); if (statusBuf.len == sizeof (int) + 1) { myExecCmdOut->status = *((int *)statusBuf.buf); free (statusBuf.buf); } childStatus = 0; #ifndef windows_platform /* UNIX */ status = waitpid (childPid, &childStatus, 0); if (status >= 0 && myExecCmdOut->status >= 0 && childStatus != 0) { rodsLog (LOG_ERROR, "_rsExecCmd: waitpid status = %d, myExecCmdOut->status = %d, childStatus = %d", status, myExecCmdOut->status, childStatus); myExecCmdOut->status = EXEC_CMD_ERROR; } } #endif return (myExecCmdOut->status); }