コード例 #1
0
ファイル: ProcessScheduling.c プロジェクト: xXFracXx/MIT-Labs
void inputProcess (MQUEUE_p_t front[MAX], MQUEUE_p_t rear[MAX], int pid, int priority, int exec_time) {

    if (priority > MAX) {
        int i = MAX;
        MAX *= 2;
        front = (MQUEUE_p_t *)realloc(front, MAX * sizeof(MQUEUE_p_t));
        rear = (MQUEUE_p_t *)realloc(front, MAX * sizeof(MQUEUE_p_t));
        for (; i < MAX; ++i) {
            *(front + i) = createProcess(0, 0, 0);
            *(rear + i) = createProcess(0, 0, 0);
        }
    }

    MQUEUE_p_t f = *(front + priority - 1);
    MQUEUE_p_t r = *(rear + priority - 1);

    MQUEUE_p_t process = createProcess(pid, priority, exec_time);
    process->link = NULL;

    if (f->link == NULL) {
        f->link = process;
        r->link = process;
    }

    else {
        MQUEUE_p_t temp = f;
        while (temp->link != NULL)
            temp = temp->link;
        temp->link = process;
        r = process;
    }
    return;
}
コード例 #2
0
ファイル: ProcessScheduling.c プロジェクト: xXFracXx/MIT-Labs
void initQueue (MQUEUE_p_t front[MAX], MQUEUE_p_t rear[MAX]) {
    int i;
    for (i = 0; i < MAX; ++i) {
        *(front + i) = createProcess(0, 0, 0);
        *(rear + i) = createProcess(0, 0, 0);
    }
}
コード例 #3
0
int main()
{
  double T(1e-1);
  double L(1e-6);
  double N(1e+4);
  double R(2.5e-9);
  double D(1e-12);
  double stirTime(T*0.5);

  libecs::initialize();
  libecs::Model& 
    model(*(new libecs::Model(*libecs::createDefaultModuleMaker())));
  model.setup();
  libecs::Stepper& stepper(*model.createStepper("SpatiocyteStepper", "SS"));
  stepper.setProperty("VoxelRadius", libecs::Polymorph(R)); 
  stepper.setProperty("ThreadSize", libecs::Polymorph(libecs::Integer(2))); 
  model.getRootSystem()->setProperty("StepperID", libecs::Polymorph("SS"));
  createVariable(model, "Variable:/:GEOMETRY", CUBOID);
  createVariable(model, "Variable:/:LENGTHX", L);
  createVariable(model, "Variable:/:LENGTHY", L);
  createVariable(model, "Variable:/:LENGTHZ", L);
  createVariable(model, "Variable:/:XYPLANE", PERIODIC);
  createVariable(model, "Variable:/:XZPLANE", PERIODIC);
  createVariable(model, "Variable:/:YZPLANE", PERIODIC);
  createVariable(model, "Variable:/:VACANT", 0);

  createVariable(model, "Variable:/:A", N);
  createVariable(model, "Variable:/:B", 0); 
  
  /*
  libecs::Process& vis(createProcess(model, "VisualizationLogProcess",
                                     "Process:/:logger"));
  vis.registerVariableReference("_", libecs::String("Variable:/Surface:A"), 0);
  vis.registerVariableReference("_", libecs::String("Variable:/Surface:As"), 0);
  vis.loadProperty("LogInterval", libecs::Polymorph(0.01));
  */

  libecs::Process& pop(createProcess(model, "MoleculePopulateProcess",
                                     "Process:/:pop"));
  pop.registerVariableReference("_", libecs::String("Variable:/:A"), 0);

  libecs::Process& dif(createProcess(model, "DiffusionProcess",
                                     "Process:/:diffuseA"));
  dif.registerVariableReference("_", libecs::String("Variable:/:A"), 0);
  dif.loadProperty("D", libecs::Polymorph(D));

  model.initialize();
  run(model, stirTime);
  boost::posix_time::ptime start(
                 boost::posix_time::microsec_clock::universal_time());
  run(model, T);
  boost::posix_time::ptime end(
                 boost::posix_time::microsec_clock::universal_time());
  std::cout << "duration:" << end-start << std::endl;
  delete &model;
  libecs::finalize(); 
}
コード例 #4
0
int main() {
    IOWR_ALTERA_AVALON_PIO_DATA(LED_COLOR_BASE, LED_COLOR_RESET_VALUE);
    initBuffer(&b0);
    createProcess(producer, STACK_SIZE);
    createProcess(consumer, STACK_SIZE);
    createProcess(countAndDisplay, STACK_SIZE);

    start();
    return 0;
}
コード例 #5
0
ファイル: main.cpp プロジェクト: vmezhang/sometest
int main(int argc, char *argv[])
{

	list_entry_t *pos;
	int byteStart, byteEnd, globalEnd;
	struct ProcStruct *next;

	schedInit();                                          //init schedule 
  
	printf("SchedInit finished!\n");
	
	cpu_init();                                          //init cpu
 
	printf("Cpu init finished!\n");

	initProcList();                                      //runnbale process 
 
	printf("Init process list finished!\n");

	procInit();                                          //init process table

	printf("The first proc init finished!\n");

	initWaitQueue();                                     //init wait queue

	printf("Init wait queue finished!\n");

	bc_read(&byteStart, &byteEnd, &globalEnd);           //读取字节码

	/*
	for (int i = 0; i < 7; i++) {
		printf("%d %d %d\n", byte_code[i].code, byte_code[i].arg1, byte_code[i].arg2);
	}
*/
	createProcess(byteStart, byteEnd, globalEnd);        //根据字节码的初始下标和终止下标创建第一个进程

//	createProcess(0, 9, 3);                              //根据字节码的初始下标和终止下标创建第一个进程

	printCurrent();

	addRunEqueue();                                     //将创建的进程加入到就绪队列
	
	printf("The proc addRunEqueu finished!\n");


	    while (cpu_state != 0 && rq->proc_num)
	    {
		    printf("schedul start...\n");
		    cpuSchedProc();
	    }
	    while (rq->proc_num == 0 && wq->wait_num != 0)
	    {
		    next = waitQueuePickNext(wq);
		    delWaitQueue(wq, next);
		    schedClassEnqueue(next);
		    schedule();
	    }
	
	return 0;
}
コード例 #6
0
void MainWidget::setupClicked()
{
	if (ui->setupName->text().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	QStringList args;
	args << "setup";
	if (!ui->setupNem->text().isEmpty())
	{
		args << "--nem" << ui->setupNem->text();
	}
	if (!ui->setupCurse->text().isEmpty())
	{
		args << "--curse" << ui->setupCurse->text();
	}
	if (!ui->setupServer->text().isEmpty())
	{
		args << "--server" << ui->setupServer->text();
	}
	args << ui->setupName->text();
	process->setArguments(args);
	startProcess(process);
}
コード例 #7
0
void ProcessRegistry::Run()
{
  if (!progs_ || !progs_[0])
    return;

  debug(MOUNTMINIX, "mounting userprog-partition \n");

  vfs_syscall.mkdir("/usr", 0);
  debug(MOUNTMINIX, "mkdir /usr\n");
  vfs_syscall.mount("idea1", "/usr", "minixfs", 0);
  debug(MOUNTMINIX, "mount idea1\n");

  for (uint32 i = 0; progs_[i]; i++)
  {
    createProcess(progs_[i]);
  }

  counter_lock_.acquire();

  while (progs_running_)
    all_processes_killed_.wait();

  counter_lock_.release();

  debug(MOUNTMINIX, "unmounting userprog-partition because all processes terminated \n");

  vfs_syscall.umount("/user_progs", 0);

  kill();
}
コード例 #8
0
ファイル: bp_cl.cpp プロジェクト: pkesist/buildpal
int runLocallyFallback( char const * reason, void * vpCompilerExe )
{
    char const * compilerExecutable = static_cast<char const *>( vpCompilerExe );
    std::cerr
        << "ERROR: " << reason << "\nRunning command locally...\n";
    return createProcess( compilerExecutable, GetCommandLineA() );
}
コード例 #9
0
		virtual void construct(std::shared_ptr<library::XML> xml) override
		{
			//--------
			// CONSTRUCT ROLES
			//--------
			// CLEAR ORDINARY ROLES
			process_map_.clear();

			// CREATE ROLES
			if (xml->has("processes") == true && xml->get("processes")->front()->has("process") == true)
			{
				std::shared_ptr<library::XMLList> &role_xml_list = xml->get("processes")->front()->get("process");
				for (size_t i = 0; i < role_xml_list->size(); i++)
				{
					std::shared_ptr<library::XML> &role_xml = role_xml_list->at(i);

					// CONSTRUCT ROLE FROM XML
					std::shared_ptr<DistributedProcess> role(createProcess(role_xml));
					role->construct(role_xml);

					// AND INSERT TO ROLE_MAP
					insertProcess(role);
				}
			}

			//--------
			// CONSTRUCT SYSTEMS
			//--------
			super::construct(xml);
		};
コード例 #10
0
void MainWidget::verifyClicked()
{
	if (files().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	process->setArguments(QStringList() << "verify" << files());
	startProcess(process);
}
コード例 #11
0
ファイル: Process.cpp プロジェクト: ksergy1/OnPosix
/**
 * \brief Constructor to run a specific function
 *
 * This constructor creates a new process that will run the
 * function given as argument.
 * @param function: pointer to the function that must be run
 */
Process::Process(void (*function)(void)):
    is_child_(false),
    running_(false),
    status_(0)
{
	createProcess();
	if (is_child_ && running_){
		(*function)();
	}
}
コード例 #12
0
ファイル: versioncontrol.cpp プロジェクト: cornelius/todoodle
bool VersionControl::updateDirectory()
{
  createProcess();
  
  mCommand = Update;
  
  mArguments << "up";
  
  return startProcess();
}
コード例 #13
0
ファイル: versioncontrol.cpp プロジェクト: cornelius/todoodle
bool VersionControl::commitDirectory( const QString &log )
{
  createProcess();

  mCommand = Commit;

  mArguments << "ci" << "-m" << log;

  return startProcess();
}
コード例 #14
0
ファイル: versioncontrol.cpp プロジェクト: cornelius/todoodle
bool VersionControl::addFile( const QString &filename )
{
  createProcess();

  mCommand = Add;

  mArguments << "add" << filename;

  return startProcess();
}
コード例 #15
0
ファイル: processManager.c プロジェクト: Bromind/ANFK
/*
 * Instanciate Lists & idle process
 */
void initManager(void)
{
	stoppedList.head = 0;
	stoppedList.size = 0;
	runningList.head = 0;
	runningList.size = 0;
	LOG("creating idle process\n");
	struct cell * idleCell = createProcess(&idleProcess, 0);
	start(idleCell);
}
コード例 #16
0
ファイル: Model.cpp プロジェクト: ecell/ecell3
Entity* Model::createEntity( String const& aClassname, FullID const& aFullID )
{
    if( aFullID.getSystemPath().isModel() )
    {
        THROW_EXCEPTION( BadSystemPath, "empty SystemPath" );
    }

    System* aContainerSystemPtr( getSystem( aFullID.getSystemPath() ) );
    Entity* retval( 0 );

    if ( !aContainerSystemPtr )
    {
        THROW_EXCEPTION( BadSystemPath,
                         "[" + aFullID.getSystemPath().asString()
                         + "] cannot be reached" );
    }
 
    switch( aFullID.getEntityType() )
    {
    case EntityType::VARIABLE:
        {
            retval = createVariable( aClassname );
            retval->setID( aFullID.getID() );
            aContainerSystemPtr->registerEntity(
                    static_cast< Variable* >( retval ) );
        }
        break;

    case EntityType::PROCESS:
        {
            retval = createProcess( aClassname );
            retval->setID( aFullID.getID() );
            aContainerSystemPtr->registerEntity(
                    static_cast< Process* >( retval ) );
        }
        break;

    case EntityType::SYSTEM:
        {
            retval = createSystem( aClassname );
            retval->setID( aFullID.getID() );
            aContainerSystemPtr->registerEntity(
                    static_cast< System* >( retval ) );
        }
        break;

    default:
        THROW_EXCEPTION( InvalidEntityType, "invalid EntityType specified" );
    }

    return retval;
}
コード例 #17
0
ファイル: priorityQueue.c プロジェクト: Oldkin/CSC311-2015
void testPriorityQueue() {
  PriorityQueuePointer pq = createPriorityQueue( 12 );
  printf( "Is newly created income empty? %d\n\n", 
    isPriorityQueueEmpty(pq) );


  pqEnqueue( pq, createProcess(2,3) );
  pqEnqueue( pq, createProcess(2,3) );
  pqEnqueue( pq, createProcess(2,3) );
  pqEnqueue( pq, createProcess(2,3) );
  pqEnqueue( pq, createProcess(2,3) );

  printPriorityQueue( pq );

  printf( "\n" );

  while( !isPriorityQueueEmpty(pq) ) {
    ProcessPointer pp = pqDequeue( pq );
    printf( "highest priority item = %8.4f\n", pp->serviceTime );
  } // while

} // testPriorityQueue()
コード例 #18
0
// ----------------------------------------------------------------------------
void LocalEvaluator::reset()
{
  //setWorkingDir( "" );

  disconnect( process, SIGNAL( error(QProcess::ProcessError) ), this, SLOT( onProcessError(QProcess::ProcessError) ) );
  disconnect( process, SIGNAL( readyRead() ), this, SLOT( onProcessOutput() ) );
  disconnect( process, SIGNAL( finished(int) ), this, SLOT( exit(int) ) );

  kill();
  process->deleteLater();

  createProcess();
  startJulia();
}
コード例 #19
0
ファイル: myseqdist.cpp プロジェクト: Cryomics-Lab/mothur
int correctDist::execute(string distanceFileName){
	try {
#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
#else
		processors = 1;
#endif
		correctMatrix.resize(4);
		for(int i=0;i<4;i++){	correctMatrix[i].resize(4);	}
		
		correctMatrix[0][0] = 0.000000;		//AA
		correctMatrix[1][0] = 11.619259;	//CA
		correctMatrix[2][0] = 11.694004;	//TA
		correctMatrix[3][0] = 7.748623;		//GA
		
		correctMatrix[1][1] = 0.000000;		//CC
		correctMatrix[2][1] = 7.619657;		//TC
		correctMatrix[3][1] = 12.852562;	//GC
		
		correctMatrix[2][2] = 0.000000;		//TT
		correctMatrix[3][2] = 10.964048;	//TG
		
		correctMatrix[3][3] = 0.000000;		//GG
		
		for(int i=0;i<4;i++){
			for(int j=0;j<i;j++){
				correctMatrix[j][i] = correctMatrix[i][j];
			}
		}
		
		numSeqs = names.size();
				
		if(processors == 1){ driver(0, numSeqs, distanceFileName); }
		else{
			
			for(int i=0;i<processors;i++){
				start.push_back(int (sqrt(float(i)/float(processors)) * numSeqs));
				end.push_back(int (sqrt(float(i+1)/float(processors)) * numSeqs));
			}
			
			createProcess(distanceFileName);
		}
		
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "correctDist", "execute");
		exit(1);
	}
}
コード例 #20
0
ファイル: FileSystemServiceImpl.cpp プロジェクト: xcodez/jsfs
	virtual void run() {
		BException rex;
		HANDLE hProcess = NULL;

		try {

			wstring params = makeValidParams(args);

			wstring fileToOpen = jsfs->makeValidPath(args->at(0));

			PExecuteNotifyInfo notifyInfo;
			pwstring pstandardOut, pstandardError;
			if (notify) {
				notifyInfo = PExecuteNotifyInfo(new ExecuteNotifyInfo());
			}

			if (execOpts->getStandardInput().size() || (notifyInfo && (execOpts->getCaptureOutput() || execOpts->getCaptureError()))) {

				if (notifyInfo && execOpts->getCaptureOutput()) pstandardOut = pwstring(new wstring());
				if (notifyInfo && execOpts->getCaptureError()) pstandardError = pwstring(new wstring());

				createProcess(fileToOpen, params, execOpts->getStandardInput(), pstandardOut, pstandardError);
			}
			else {
				shellExecute(fileToOpen, params);
			}

			if (notifyInfo) {
				PFileSystemNotify notifyService = jsfs->getNotifyService();
				if (notifyService) {
					notifyInfo->setExtraInfo(execOpts->getExtraInfo());

					if (pstandardOut) notifyInfo->setStandardOutput(*pstandardOut);
					if (pstandardError) notifyInfo->setStandardError(*pstandardError);

					notifyService->notify(notifyInfo);
				}
			}
		}
		catch (const BException& ex) {
			rex = ex;
		}
	
		if (hProcess) ::CloseHandle(hProcess);

		if (rex) {
			throw rex;
		}
	}
コード例 #21
0
ファイル: create.c プロジェクト: oscarhou/secretrepo
int createIdle(void (*func)(), int stack)
{
    struct pcbHeader *pcb = createProcess(func, stack);
    int rc = 0;
    if (pcb == NULL)
    {
        kprintf("Error creating a process\n");
        rc = -1;
    }
    else
    {
        idle = pcb;
        rc = pcb->pid;
    }
    return rc;
} 
コード例 #22
0
void MainWidget::updateClicked()
{
	if (files().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	QStringList args;
	args << "update";
	if (ui->updateNetworkBtn->isChecked())
	{
		args << "--no-network";
	}
	args << files();
	process->setArguments(args);
	startProcess(process);
}
コード例 #23
0
ファイル: queue.c プロジェクト: AriLoveless/CSC311-2015
// Create a queue and fill it with a specified
// number of processes.
QueuePointer buildQueue( int numberOfProcesses ) {
  seedRandomNumberGenerator();

  QueuePointer qp = createQueue();

  double elapsedTime = 0.0;
  int i;
  for( i = 0; i < numberOfProcesses; i++ ) {
    ProcessPointer pp = createProcess( MEAN_SERVICE_TIME,
        MEAN_INTERARRIVAL_TIME );
    elapsedTime += pp->interarrivalTime;
    pp->arrivalTime = elapsedTime;
    enqueue( qp, pp );
  } // for

  return qp;
} // buildQueue( int )
コード例 #24
0
void MainWidget::createIndexClicked()
{
	if (files().isEmpty())
	{
		return;
	}
	QProcess *process = createProcess();
	QStringList args;
	args << "create-index";
	if (!ui->createIndexBaseUrl->text().isEmpty())
	{
		args << "--base" << ui->createIndexBaseUrl->text();
	}
	args << files();
	process->setArguments(args);
	startProcess(process);
}
コード例 #25
0
/**
@brief This function handles a system call request coming from a process running in Kernel Mode.
@return Void.
*/
HIDDEN void syscallKernelMode()
{
	/* Identify and handle the system call */
	switch (SYSBP_Old->a1)
	{
		case CREATEPROCESS:
			CurrentProcess->p_s.a1 = createProcess((state_t *) SYSBP_Old->a2);
			break;

		case TERMINATEPROCESS:
			terminateProcess();
			break;

		case VERHOGEN:
			verhogen((int *) SYSBP_Old->a2);
			break;

		case PASSEREN:
			passeren((int *) SYSBP_Old->a2);
			break;

		case GETCPUTIME:
			CurrentProcess->p_s.a1 = getCPUTime();
			break;

		case WAITCLOCK:
			waitClock();
			break;

		case WAITIO:
			CurrentProcess->p_s.a1 = waitIO((int) SYSBP_Old->a2, (int) SYSBP_Old->a3, (int) SYSBP_Old->a4);
			break;

		case SPECTRAPVEC:
			specTrapVec((int) SYSBP_Old->a2, (state_t *) SYSBP_Old->a3, (state_t *) SYSBP_Old->a4);
			break;

		default:
			/* Distinguish whether SYS5 has been invoked or not */
			checkSYS5(SYSBK_EXCEPTION, SYSBP_Old);
	}

	/* Call the scheduler */
	scheduler();
}
コード例 #26
0
ファイル: Process.cpp プロジェクト: ksergy1/OnPosix
/**
 * \brief Constructor to run a specific program
 *
 * This constructor creates a new process that will run the
 * program given as argument. This contructor invokes fork()+execvp().
 * @param program: name of the program to be run
 * @args args: list of arguments
 */
Process::Process(const std::string& program, 
    const std::vector<std::string>& args):
    is_child_(false),
    running_(false),
    status_(0)
{
	createProcess();
	if (is_child_ && running_){
		char* c_args [20];
		c_args[0] = const_cast<char*> (program.c_str());
		for (unsigned int i = 0; i < args.size(); ++i){
			c_args[i+1] = const_cast<char*> (args[i].c_str());
		}
		c_args[args.size()+1] = (char*) NULL;

		execvp(program.c_str(), c_args);
	}
}
コード例 #27
0
jobject Java_org_androix_nativenetbook_NativeInit_createProcess(JNIEnv *env, jobject cls, jintArray pidArray)
{
	int ptm;
	int pid = -1;
	int pidLen;
	int *ppid = NULL;
	jboolean copy;

	jclass FileDescriptor_class;
	jmethodID FileDescriptor_init;
	jfieldID FileDescriptor_descriptor;

	jobject filedescriptor;	

	LOG("[native] createProcess");

	FileDescriptor_class = (*env)->FindClass(env, "java/io/FileDescriptor");
	FileDescriptor_descriptor = (*env)->GetFieldID(env, FileDescriptor_class, "descriptor", "I");
	FileDescriptor_init = (*env)->GetMethodID(env, FileDescriptor_class, "<init>", "()V");

	ptm = createProcess(&pid);
	
	if (pidArray) {
		pidLen = (*env)->GetArrayLength(env, pidArray);
		if (pidLen > 0) {
			ppid = (int *) (*env)->GetPrimitiveArrayCritical(env, pidArray, &copy);
			if (ppid) {
				*ppid = pid;
				(*env)->ReleasePrimitiveArrayCritical(env, pidArray, ppid, 0);
			}
		}
	}

	filedescriptor = (*env)->NewObject(env, FileDescriptor_class, FileDescriptor_init);
	if (filedescriptor) {
		(*env)->SetIntField(env, filedescriptor, FileDescriptor_descriptor, ptm);
	} 

	return filedescriptor;	
}
コード例 #28
0
bool WhmShellProcess::run(WhmShellContext *sc)
{
	WhmShellCommand *c = command;
	bool result = true;	
	Token_t token = NULL;
#ifndef HTTP_PROXY
	if (runAsUser) {
		//创建运行身份令牌
		if (sc->vh==NULL) {
			sc->last_error = 128;
			return false;
		}
		token = sc->vh->createToken(result);
		if(!result){
			sc->last_error = 129;
			return false;
		}
	}
#endif
	//the commands stdout pipe
	PIPE_T big_stdout_pipe[2];
	if (!KPipeStream::create(big_stdout_pipe)) {
		if (token) {
			KVirtualHost::closeToken(token);
		}
		return false;
	}
	//the commands stdin pipe
	PIPE_T big_stdin_pipe[2];
	bool big_stdin_pipe_created = false;
	//init the std file
	PIPE_T hstdin = get_stdin(sc);
	if (hstdin==INVALIDE_PIPE && sc->in_buffer.getLen()>0) {
		//如果没有输入文件并且输入有数据。就要创建输入管道
		if (!KPipeStream::create(big_stdin_pipe)) {
			//关闭打开的big_stdout_pipe
			ClosePipe(big_stdout_pipe[0]);
			ClosePipe(big_stdout_pipe[1]);
			if (token) {
				KVirtualHost::closeToken(token);
			}
			return false;
		}
		big_stdin_pipe_created = true;
		hstdin = big_stdin_pipe[READ_PIPE];
	}
	PIPE_T hstdout = get_stdout(sc);
	PIPE_T hstderr = get_stderr(sc);
	PIPE_T in,out,err;
	err = hstderr;
	if (err==INVALIDE_PIPE) {
		err = big_stdout_pipe[WRITE_PIPE];
	}
	PIPE_T pp[2];
	for(int i=0;i<2;i++){
		pp[i] = INVALIDE_PIPE;
	}
	while (c) {
		char **arg = c->makeArgs(sc);
		KCmdEnv *env = c->makeEnv(sc);
		pid_t pid;
		kfinit(pid);
		//set in
		if (c==command) {
			in = hstdin;
		} else {
			assert(pp[READ_PIPE]!=INVALIDE_PIPE);
			in = pp[READ_PIPE];
			pp[READ_PIPE] = INVALIDE_PIPE;
			assert(pp[WRITE_PIPE]!=INVALIDE_PIPE);
			//close the out pipe
			ClosePipe(pp[WRITE_PIPE]);
			pp[WRITE_PIPE] = INVALIDE_PIPE;
		}
		//set out
		if (c->next) {
			//create a new pipe
			if (!KPipeStream::create(pp)) {
				if (c!=command) {
					ClosePipe(in);
				}
				break;
			}
			out = pp[WRITE_PIPE];
		} else {
			//if the command is last.
			//then set the out to big_pipe
			out = hstdout;
			if (out==INVALIDE_PIPE) {
				out = big_stdout_pipe[WRITE_PIPE];
			}
		}
		char *curdir2 = NULL;
		if (curdir) {
			curdir2 = sc->parseString(curdir);
		}
		result = createProcess(token,arg,env,curdir2,in,out,err,pid);
		if (curdir2) {
			free(curdir2);
		}
		if (c!=command) {
			//close the in pipe
			ClosePipe(in);
		}
		//free args
		for (int i=0;;i++) {
			if(arg[i]==NULL){
				break;
			}
			free(arg[i]);
		}
		delete[] arg;
		if (env) {
			delete env;
		}	
		sc->setLastPid(pid);
		if (!result) {
			sc->last_error = 127;
			break;
		}	
		c = c->next;
	}
	//关闭输入,输出父进程无用的管道端
	if (kflike(hstdin)) {
		ClosePipe(hstdin);
	}
	ClosePipe(big_stdout_pipe[WRITE_PIPE]);
	//处理输入
	if (big_stdin_pipe_created) {
		if (result) {
			//创建成功才写入数据
			buff *buf = sc->in_buffer.getHead();
			while (buf && buf->data) {
				if (write_pipe(big_stdin_pipe[WRITE_PIPE],buf->data,buf->used)!=buf->used) {
					break;
				}
				buf = buf->next;
			}
		}
		//清理输入数据和管道资源
		sc->in_buffer.destroy();
		ClosePipe(big_stdin_pipe[WRITE_PIPE]);
	}
	//处理输出
	if (result && (hstdout==INVALIDE_PIPE || hstderr==INVALIDE_PIPE)) {
		for (;;) {
			char buf[512];
			int len = read_pipe(big_stdout_pipe[READ_PIPE],buf,512);
			if (len<=0) {
				break;
			}
			sc->lock.Lock();
			if (sc->out_buffer.getLen() > 1048576) {
				//the out msg is too large.drop it.
				sc->lock.Unlock();
				fwrite(buf,1,len,stdout);
			} else {
				sc->out_buffer.write_all(buf,len);
				sc->lock.Unlock();
			}
			//fwrite(buf,1,len,stdout);	
		}
	}
	if (kflike(hstdout)) {
		ClosePipe(hstdout);
	}
	if (kflike(hstderr)) {
		ClosePipe(hstderr);
	}
	ClosePipe(big_stdout_pipe[READ_PIPE]);
	if (token) {
		KVirtualHost::closeToken(token);
	}
#ifdef _WIN32
	if (kflike(sc->last_pid)) {
		WaitForSingleObject(sc->last_pid,INFINITE);
	}
#endif
	return result;
}
コード例 #29
0
ファイル: main.c プロジェクト: chalmerj/comp410-demosh
int main (int argc, const char * argv[])
{
    char buffer[MAX_BUFFER];
    Command_t cmd = {NULL, 0, {NULL}};
    Process_t *psList;
    int runningTime = 0;
    
    memset((void *)&psList, 0, sizeof(psList));
    
    psList = createProcess(psList, "Parent", NULL, getpid(), time(NULL));
        
       
    //pid_t   pid = 0;
    
    while (1){
        memset((void *) buffer, 0, sizeof(buffer));
        
        printf("$ ");
        if(!fgets(buffer, MAX_BUFFER, stdin)) break;
        
        // Trim the trailing \n from the buffer
        char *ptr;
        if((ptr = strchr(buffer, '\n')) != NULL) *ptr = '\0';
        
        //Parse the command input
        parseInput(buffer, &cmd);
        
//        printf("Command: %s\nNum. Args: %d\n",cmd.command, cmd.argc);
//        printf("Command Code:%d\n",cmd.cmdCode);
        
        switch (cmd.cmdCode)
        {
            case 0:
                break;
                
            case CMD_EXIT:
                return 0;
            
            case CMD_LIST:
                list(psList);
                break;
            
            case CMD_SLEEP:
                if (!cmdSleep(psList, &cmd))
                {
                    printf("Sleep thread created\n");
                    break;
                }
                else
                {
                    printf("Sleep thread failed\n");
                    break;
                }
                
            case CMD_TIME:
                runningTime = cmdTime(psList,&cmd);
                if (0 < runningTime)
                {
                    printf("PID %s running for %ds.\n",
                           cmd.argv[1],runningTime); 
                }
                else
                {
                    printf("Time Error\n");
                }
                break;
            
            case CMD_HELP:
                printf("List of Commands:\n");
                printf("list - list the running threads.\n");
                printf("sleep n - create a new sleeping thread for 'n' seconds.\n");
                printf("time PID - give the current running time for thread PID.\n");
                printf("wait PID - block execution until thread PID terminates.\n");
                printf("wait-list PID PID ... - block execution until each PID given terminates.\n");
                printf("kill PID - terminates thread PID.\n");
                printf("exit - exit the program.\n");
                printf("help  - print this help.\n");
                break;
                
                
            default:
                break;
                    
        }

    }
}
コード例 #30
0
ファイル: ConEmuCmd.cpp プロジェクト: robovod/ConEmu
int ComspecInit()
{
    TODO("Определить код родительского процесса, и если это FAR - запомнить его (для подключения к пайпу плагина)");
    TODO("Размер получить из GUI, если оно есть, иначе - по умолчанию");
    TODO("GUI может скорректировать размер с учетом полосы прокрутки");
    WARNING("CreateFile(CONOUT$) по идее возвращает текущий ScreenBuffer. Можно его самим возвращать в ComspecDone");

    // Правда нужно проверить, что там происходит с ghConOut.Close(),...
    // Размер должен менять сам GUI, через серверный ConEmuC!
#ifdef SHOW_STARTED_MSGBOX
    MessageBox(GetConEmuHWND(2), L"ConEmuC (comspec mode) is about to START", L"ConEmuC.ComSpec", 0);
#endif
    //int nNewBufferHeight = 0;
    //COORD crNewSize = {0,0};
    //SMALL_RECT rNewWindow = gpSrv->sbi.srWindow;
    BOOL lbSbiRc = FALSE;
    gbRootWasFoundInCon = 2; // не добавлять к "Press Enter to close console" - "or wait"
    gbComspecInitCalled = TRUE; // Нельзя вызывать ComspecDone, если не было вызова ComspecInit
    // в режиме ComSpec - запрещено!
    gbAlwaysConfirmExit = FALSE;
    gbAutoDisableConfirmExit = FALSE;
#ifdef _DEBUG
    xf_validate();
    xf_dump_chk();
#endif
    // Это наверное и не нужно, просто для информации...
    lbSbiRc = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &gpSrv->sbi);
#ifdef _DEBUG
    DWORD nErrCode = lbSbiRc ? 0 : GetLastError();
    // Процесс запущен с редиректом вывода?
    _ASSERTE(lbSbiRc || (nErrCode == ERROR_INVALID_HANDLE));
#endif

#if 0
    // 111211 - "-new_console" теперь передается в GUI и исполняется в нем
    // Сюда мы попадаем если был ключик -new_console
    // А этом случае нужно завершить ЭТОТ экземпляр и запустить в ConEmu новую вкладку
    if (gpSrv->bNewConsole)
    {
#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        PROCESS_INFORMATION pi;
        memset(&pi, 0, sizeof(pi));
        STARTUPINFOW si;
        memset(&si, 0, sizeof(si));
        si.cb = sizeof(si);
        si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USECOUNTCHARS;
        si.dwXCountChars = gpSrv->sbi.dwSize.X;
        si.dwYCountChars = gpSrv->sbi.dwSize.Y;
        si.wShowWindow = SW_HIDE;
        PRINT_COMSPEC(L"Creating new console for:\n%s\n", gpszRunCmd);
#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        // CREATE_NEW_PROCESS_GROUP - низя, перестает работать Ctrl-C
        // Запускается новый сервер (новая консоль), сюда хуки ставить не надо.
        BOOL lbRc = createProcess(TRUE, NULL, gpszRunCmd, NULL,NULL, TRUE,
                                  NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE,
                                  NULL, NULL, &si, &pi);
        DWORD dwErr = GetLastError();

        if (!lbRc)
        {
            PrintExecuteError(gpszRunCmd, dwErr);
            return CERR_CREATEPROCESS;
        }

#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        //delete psNewCmd; psNewCmd = NULL;
        AllowSetForegroundWindow(pi.dwProcessId);
        PRINT_COMSPEC(L"New console created. PID=%i. Exiting...\n", pi.dwProcessId);
        SafeCloseHandle(pi.hProcess);
        SafeCloseHandle(pi.hThread);
        DisableAutoConfirmExit();
        //gpSrv->nProcessStartTick = GetTickCount() - 2*CHECK_ROOTSTART_TIMEOUT; // менять nProcessStartTick не нужно. проверка только по флажкам
#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        return CERR_RUNNEWCONSOLE;
    }
#endif

    // Если определена ComSpecC - значит ConEmuC переопределил стандартный ComSpec
    // Вернем его
    wchar_t szComSpec[MAX_PATH+1];
    const wchar_t* pszComSpecName;

    //110202 - comspec более не переопределяется
    //if (GetEnvironmentVariable(L"ComSpecC", szComSpec, MAX_PATH) && szComSpec[0] != 0)
    WARNING("TCC/ComSpec");
    if (GetEnvironmentVariable(L"ComSpec", szComSpec, MAX_PATH) && szComSpec[0] != 0)
    {
        //// Только если это (случайно) не conemuc.exe
        //wchar_t* pwszCopy = (wchar_t*)PointToName(szComSpec); //wcsrchr(szComSpec, L'\\');
        ////if (!pwszCopy) pwszCopy = szComSpec;

        //#pragma warning( push )
        //#pragma warning(disable : 6400)
        //if (lstrcmpiW(pwszCopy, L"ConEmuC")==0 || lstrcmpiW(pwszCopy, L"ConEmuC.exe")==0
        //        /*|| lstrcmpiW(pwszCopy, L"ConEmuC64")==0 || lstrcmpiW(pwszCopy, L"ConEmuC64.exe")==0*/)
        //	szComSpec[0] = 0;
        //#pragma warning( pop )

        //if (szComSpec[0])
        //{
        //	SetEnvironmentVariable(L"ComSpec", szComSpec);
        //	SetEnvironmentVariable(L"ComSpecC", NULL);
        //}

        pszComSpecName = (wchar_t*)PointToName(szComSpec);
    }
    else
    {
        WARNING("TCC/ComSpec");
        pszComSpecName = L"cmd.exe";
    }

    lstrcpyn(gpSrv->szComSpecName, pszComSpecName, countof(gpSrv->szComSpecName));

    if (pszComSpecName)
    {
        wchar_t szSelf[MAX_PATH+1];

        if (GetModuleFileName(NULL, szSelf, MAX_PATH))
        {
            lstrcpyn(gpSrv->szSelfName, (wchar_t*)PointToName(szSelf), countof(gpSrv->szSelfName));

            if (!GetAliases(gpSrv->szSelfName, &gpSrv->pszPreAliases, &gpSrv->nPreAliasSize))
            {
                if (gpSrv->pszPreAliases)
                {
                    _wprintf(gpSrv->pszPreAliases);
                    free(gpSrv->pszPreAliases);
                    gpSrv->pszPreAliases = NULL;
                }
            }
        }
    }

    SendStarted();
    //ConOutCloseHandle()
    return 0;
}