Beispiel #1
0
int
main(int argc, char **argv)
{
	volatile int a = 0;

	while (waiting(&a) == 0)
		continue;

	if (vfork() == 0) {
		int ret = go();
		(void) _exit(ret);
	}

	return (0);
}
Beispiel #2
0
int
dotest(void)
{
	CLIENT *client;
	AUTH *auth;
	COMPOUND4args args;
	COMPOUND4res res;
	enum clnt_stat status;
	struct timeval timeout;
	nfs_argop4 arg[1];
	char *tag = "dtrace test";
	volatile int a = 0;

	while (waiting(&a) == 0)
		continue;

	timeout.tv_sec = 30;
	timeout.tv_usec = 0;

	client = clnt_create("localhost", NFS4_PROGRAM, NFS_V4, "tcp");
	if (client == NULL) {
		clnt_pcreateerror("test");
		return (1);
	}
	auth = authsys_create_default();
	client->cl_auth = auth;
	args.minorversion = 0;
	args.tag.utf8string_len = strlen(tag);
	args.tag.utf8string_val = tag;
	args.argarray.argarray_len = sizeof (arg) / sizeof (nfs_argop4);
	args.argarray.argarray_val = arg;

	arg[0].argop = OP_PUTROOTFH;
	/* no need to manipulate nfs_argop4_u */

	bzero(&res, sizeof (res));

	status = clnt_call(client, NFSPROC4_COMPOUND,
	    xdr_COMPOUND4args, (caddr_t)&args,
	    xdr_COMPOUND4res, (caddr_t)&res,
	    timeout);
	if (status != RPC_SUCCESS) {
		clnt_perror(client, "test");
		return (2);
	}

	return (0);
}
Beispiel #3
0
/** Handle stolen task */
int handle_stolen_task(struct generic_task_desc * _tweed_top_) {
    trace_event(TRACE_SUBSYS_TWEED, TRACE_EVENT_TWEED_WAIT,
                GET_THIEF(_tweed_top_)->core_id);        

    while ((_tweed_top_->balarm & TWEED_TASK_COMPLETE) == 0) {
        if (!waiting(_tweed_top_)) {
            thread_yield();
        }
    }
    trace_event(TRACE_SUBSYS_TWEED, TRACE_EVENT_TWEED_WAIT_END,
                GET_THIEF(_tweed_top_)->core_id); ; 

    // update bot
    set_bot(_tweed_top_);
    return 0;
}
Beispiel #4
0
void main(int argc, char* argv[])
{
    pid1 = fork();

    if(pid1 < 0) {
        fprintf(stderr, "Fork failed");
    }
    else if (pid1 == 0) {
        wait_mark = 1;
        signal(16,stop);
        sleep(5);
        printf("%d\n", wait_mark);
        lockf(1,F_LOCK,0);
        printf("child process 1 is killed by parent! \n");
        lockf(1,F_ULOCK,0);
        exit(0);
    }
    else {
        pid2 = fork();
        if(pid2 < 0) {
            fprintf(stderr, "Fork failed");
        }
        else if (pid2 == 0) {
            wait_mark = 1;
            signal(17,stop);
            sleep(5);
            printf("%d\n", wait_mark);
            lockf(1,F_LOCK,0);
            printf("child process 2 is killed by parent! \n");
            lockf(1,F_ULOCK,0);
            exit(0);

        }
        else {
            wait_mark = 1;
            signal(SIGINT, stop);
            waiting();
            kill(pid1,16);
            kill(pid2,17);
            wait(NULL);
            wait(NULL);
            printf("parent process is killed! \n");
            exit(0);
        }
    }
}
Beispiel #5
0
int main()
{
    int p1, p2;
    if(p1 = fork())
    {
        if(p2 = fork())
        {
            wait_mark = 1;
            signal(SIGINT, stop);
            signal(SIGALRM, alarming);
            waiting();

            kill(p1, 16);
            kill(p2, 17);

            wait(0);
            wait(0);
            printf("parent process is killed!\n");
            exit(0);
        }
        else
        {
            wait_mark = 1;
            signal(17, stop);
            signal(SIGINT, SIG_IGN);
            while(wait_mark!=0);
            lockf(1,1,0);
            printf("child process2 is killed by parent!\n");
            lockf(1,0,0);
            exit(0);
        }
    }

    else
    {
        wait_mark = 1;
        signal(16, stop);
        signal(SIGINT, SIG_IGN);
        while(wait_mark!=0);
        lockf(1, 1, 0);
        printf("child process1 is killed by parent!\n");
        lockf(1, 0, 0);
        exit(0);
    }
    return 0;
}
// -----------------------------------------------------------------------------
// CUpnpCpbSimpleDeviceDescription::ServiceDescription
// Function processing service description
// -----------------------------------------------------------------------------
//
TInt CUpnpCpbSimpleDeviceDescription::ServiceDescriptionL(CUpnpHttpMessage* aMsg)
    {
    LOG_FUNC_NAME;

    // Check if device is waiting for this service
    TBool waiting(EFalse);
    if(!iRootDevice)
        {
        iResult = KErrNotFound;
        }
    else
        {
        for( TInt servCount(0);
                servCount < iRootDevice->WaitServiceDescriptionCount(); servCount++)
            {
            if ( iRootDevice->WaitServiceDescriptionSessionId(servCount )
                     == aMsg->SessionId())
                {
                waiting = ETrue;
                break;
                }
            }
        // Waiting for service description
        if(waiting)
            {
            // Processing message
            if ( !aMsg->Is2xx())
                {
                LOGS("CUpnpCpbSimpleDeviceDescription::ServiceDescriptionL - "
                     "Wrong response recived.");
                iResult = KDisscoveryIncorrect;
                }
            else
                {
                iResult = ProcessServiceDescriptionL(aMsg);
                }
            }
        else
            {
            iResult = KErrNotFound;
            }
        }
    return iResult;
    }
void FinishingStations::processWaitingList(SimulationState& state) {
	while (!state.employees().empty() 
		&& !empty()
		&& waiting()) {
		state.employees().acquire();
		dequeue();
		acquire();

		TracerService* tracer = ServiceLocator::instance().findTracerService();
		tracer->log(state.clock().now(), "1 garment begins finishing treatment.");

		EventDispatcher* dispatcher = ServiceLocator::instance().findDispatcherService();
		RandomService<int>* random = ServiceLocator::instance().findRandomService();

		Event event(state.clock().now() + random->next(state.finishingProcTimeDist()));
		event.setHandler(new FinishingEndHandler());
		dispatcher->dispatch(event);
	}
}
Beispiel #8
0
void control( void )
{
	while (1)
	{
	 	if ( isWait() )
			waiting();	

		eleStat.dir = newDirection( eleStat.dir, eleStat.floor );

		if ( isStop( eleStat.dir, eleStat.floor ) )
			stop( eleStat.dir, eleStat.floor );


		showDir( eleStat.dir );

		if ( eleStat.dir != 0 && !isStop( eleStat.dir, eleStat.floor ) )
			move( eleStat.dir, &eleStat.floor );
	}			 
}
Beispiel #9
0
/* 
 * builtin_cmd - If the user has typed a built-in command then execute
 * it immediately.  
 */
bool builtin_cmd(job_t *last_job, int argc, char **argv) 
{

	    /* check whether the cmd is a built in command
        */

  if (!strcmp("quit", argv[0])) {
    /* Your code here */
    exit(EXIT_SUCCESS);
  }
  else if (!strcmp("jobs", argv[0])) {
    /* Your code here */
    job_t* currentJob = active_jobs_head;
    job_t* deletedJob = NULL;

    while(currentJob != NULL) {
      // print active jobs and then change notified to 0

      //if((currentJob->first_process)->completed == true && currentJob->notified == false) {

      //need to check if every process has completed for a job to be complete, not just the first process
      if (job_is_completed(currentJob) == true)
      {
        printf("%d (Completed): %s\n", currentJob->pgid, currentJob->commandinfo);
        deletedJob = currentJob;

         //currentJob->notified = true;
      }
      //otherwise it is stopped
      else if (job_is_stopped(currentJob) == true)
      {
        printf("%d (Stopped): %s\n", currentJob->pgid, currentJob->commandinfo);
      }

      else
      {
        printf("%d (Running): %s\n", currentJob->pgid, currentJob->commandinfo);
      }

      currentJob = currentJob->next;

      // delete job after it is completed, don't need to save notified 
     
      if (deletedJob != NULL) 
      {
        if (deletedJob == active_jobs_head)
        {
          active_jobs_head = deletedJob->next;
          free_job(deletedJob); //TBD warning about this?
        }
        else
        {
          delete_job(deletedJob, active_jobs_head);
        }
        deletedJob = NULL;
      }
    }
    return true;
  }

  else if (!strcmp("cd", argv[0])) {
    int chdir_return = chdir(argv[1]);
    if(chdir_return == -1) {
      printf("cd: %s: No such file or directory\n", argv[1]);
    }
    return true;
  }
  else if (!strcmp("bg", argv[0])) {
    /* Your code here */
    job_t* currentJob = active_jobs_head;
    process_t* p2;

    if(argv[1] == NULL) 
    {
      // continue most recent stopped job

      //use find_last_job
      currentJob = find_last_job(active_jobs_head);

      continue_job(currentJob);
      seize_tty(currentJob->pgid);


      p2 = currentJob->first_process;

      while(p2 != NULL)
      {
        p2->stopped = false;
        
        struct sigaction action;
        action.sa_sigaction = sighandler;

        sigfillset(&action.sa_mask);
        action.sa_flags = SA_SIGINFO;
        sigaction(SIGCHLD, &action, NULL);

        p2 = p2->next;
      }
      seize_tty(getpid());
    }

    else 
    {
      pid_t job_number = atoi(argv[1]);

      
      while(currentJob != NULL) {
        // Need to eventually iterate through all processes?
        
        if((job_is_stopped(currentJob)) && currentJob->pgid == job_number) {
          //seize_tty(currentJob->pgid);
          continue_job(currentJob); 
          seize_tty(currentJob->pgid);

          p2 = currentJob->first_process;
          while (p2 != NULL)
          {
            p2->stopped = false; 

            struct sigaction action;
            action.sa_sigaction = sighandler;

            sigfillset(&action.sa_mask);
            action.sa_flags = SA_SIGINFO;
            sigaction(SIGCHLD, &action, NULL);
            p2 = p2->next;
          }

          seize_tty(getpid());
          break;
        }
        else if (currentJob->pgid == job_number) {
          printf("%s\n", "This process wasn't stopped`");
        }
        else {
          printf("%s\n", "This job number is not the requested one");
        }
        currentJob = currentJob->next;
      }
    }
    return true;
  }


  else if (!strcmp("fg", argv[0])) {
    /* Your code here */
    job_t* currentJob = active_jobs_head;
    process_t* p2;

    if(argv[1] == NULL) {
      // continue most recent stopped job

      //use find_last_job
      currentJob = find_last_job(active_jobs_head);
      continue_job(currentJob);
      seize_tty(currentJob->pgid);


      p2 = currentJob->first_process;

      while(p2 != NULL)
      {
        waiting(p2);
        p2 = p2->next;
      }
      seize_tty(getpid());
    }
    else {
      pid_t job_number = atoi(argv[1]);

      
      while(currentJob != NULL) {
        
        
        if((job_is_stopped(currentJob)) && currentJob->pgid == job_number) {
          //seize_tty(currentJob->pgid);
          continue_job(currentJob); 
          seize_tty(currentJob->pgid);

          p2 = currentJob->first_process;
          while (p2 != NULL)
          {
            waiting(p2);
            p2 = p2->next;
          }
          seize_tty(getpid());
          break;
        }
        else if (currentJob->pgid == job_number) {
          printf("%s\n", "This process wasn't stopped`");
        }
        else {
          printf("%s\n", "This job number is not the requested one");
        }
        currentJob = currentJob->next;
      }
    }
    return true;
  }
  /* not a builtin command */
  return false;
}
Beispiel #10
0
int frmMain::ReconnectServer(pgServer *server, bool restore)
{
    // Create a server object and connect it.
    wxBusyInfo waiting(wxString::Format(_("Connecting to server %s (%s:%d)"),
        server->GetDescription().c_str(), server->GetName().c_str(), server->GetPort()), this);

    // Give the UI a chance to redraw
    wxSafeYield();
    wxMilliSleep(100);
    wxSafeYield();

    int res = server->Connect(this, true);

    // Check the result, and handle it as appropriate
    wxTreeItemId item;
    switch (res)
    {
        case PGCONN_OK:
        {
            if (restore && server->GetRestore())
                StartMsg(_("Restoring previous environment"));
            else
                StartMsg(_("Establishing connection"));

            wxLogInfo(wxT("pgServer object initialised as required."));

            server->ShowTreeDetail(browser);

            browser->Freeze();
            if (restore && server->GetRestore())
                item=RestoreEnvironment(server);
            else
                item = server->GetId();
            browser->Thaw();

            if (item)
            {
                browser->SelectItem(item);

                wxSafeYield();
                browser->Expand(item);
                browser->EnsureVisible(item);
            }

            if (item)
                EndMsg(true);
            else
            {
                if (restore && server->GetRestore())
                    EndMsg(false);
                else
                    EndMsg(true);
            }
            if (item)
                GetMenuFactories()->CheckMenu((pgObject *)browser->GetItemData(item), GetMenuBar(), (ctlMenuToolbar *)GetToolBar());
            else
                GetMenuFactories()->CheckMenu(server, GetMenuBar(), (ctlMenuToolbar *)GetToolBar());
            return res;
        }
        case PGCONN_DNSERR:
            /*
            // looks strange to me. Shouldn_t server be removed from the tree as well?
            delete server;
            OnAddServer(wxCommandEvent());
            break;
            */
        case PGCONN_BAD:
            ReportConnError(server);
            break;

        default:
            wxLogInfo(wxT("pgServer object didn't initialise because the user aborted."));
            break;
    }

    server->Disconnect(this);
    return res;
}
Beispiel #11
0
bool frmMain::CheckAlive()
{
    bool userInformed = false;
    bool closeIt = false;

    wxTreeItemIdValue foldercookie;
    wxTreeItemId folderitem = browser->GetFirstChild(browser->GetRootItem(), foldercookie);
    while (folderitem)
    {
        if (browser->ItemHasChildren(folderitem))
        {
            wxCookieType cookie;
            wxTreeItemId serverItem=browser->GetFirstChild(folderitem, cookie);
            while (serverItem)
            {
                pgServer *server=(pgServer*)browser->GetObject(serverItem);

                if (server && server->IsCreatedBy(serverFactory) && server->connection())
                {
                    if (server->connection()->IsAlive())
                    {
                        wxCookieType cookie2;
                        wxTreeItemId item = browser->GetFirstChild(serverItem, cookie2);
                        while (item)
                        {
                            pgObject *obj=browser->GetObject(item);
                            if (obj && obj->IsCreatedBy(databaseFactory.GetCollectionFactory()))
                            {
                                wxCookieType cookie3;
                                item = browser->GetFirstChild(obj->GetId(), cookie3);
                                while (item)
                                {
                                    pgDatabase *db=(pgDatabase*)browser->GetObject(item);
                                    if (db && db->IsCreatedBy(databaseFactory))
                                    {
                                        pgConn *conn=db->GetConnection();
                                        if (conn)
                                        {
                                            if (!conn->IsAlive() && (conn->GetStatus() == PGCONN_BROKEN || conn->GetStatus() == PGCONN_BAD))
                                            {
                                                conn->Close();
                                                if (!userInformed)
                                                {
                                                    wxMessageDialog dlg(this, _("Do you want to attempt to reconnect to the database?"),
                                                    wxString::Format(_("Connection to database %s lost."), db->GetName().c_str()), 
                                                        wxICON_EXCLAMATION|wxYES_NO|wxYES_DEFAULT);

                                                    closeIt = (dlg.ShowModal() == wxID_NO);
                                                    userInformed = true;
                                                }
                                                if (closeIt)
                                                {
                                                    db->Disconnect();
                                                    
                                                    browser->DeleteChildren(db->GetId());
                                                    db->UpdateIcon(browser);
                                                }
	        									else 
	        									{
                                                    // Create a server object and connect it.
                                                    wxBusyInfo waiting(wxString::Format(_("Reconnecting to database %s"),
                                                        db->GetName().c_str()), this);

                                                    // Give the UI a chance to redraw
                                                    wxSafeYield();
                                                    wxMilliSleep(100);
                                                    wxSafeYield();

	        										if (!conn->Reconnect())
                                                    {
                                                        db->Disconnect();
                                                    
                                                        browser->DeleteChildren(db->GetId());
                                                        db->UpdateIcon(browser);
                                                    }
                                                    else
                                                        // Indicate things are back to normal
                                                        userInformed = false;
	        									}

                                            }
                                        }
                                    }
                                    item = browser->GetNextChild(obj->GetId(), cookie3);
                                }
                            }
                            item = browser->GetNextChild(serverItem, cookie2);
                        }
                    }
                    else
                    {
                        if (server->connection()->GetStatus() == PGCONN_BROKEN || server->connection()->GetStatus() == PGCONN_BAD)
                        {
                            server->connection()->Close();
                            if (!userInformed)
                            {
                                wxMessageDialog dlg(this, _("Do you want to attempt to reconnect to the server?"),
                                    wxString::Format(_("Connection to server %s lost."), server->GetName().c_str()), 
                                    wxICON_EXCLAMATION|wxYES_NO|wxYES_DEFAULT);

                                closeIt = (dlg.ShowModal() == wxID_NO);
                                userInformed = true;
                            }
                            if (closeIt)
                            {
                                server->Disconnect(this);
                                browser->SelectItem(serverItem);
                                execSelChange(serverItem, true);
                                browser->DeleteChildren(serverItem);
                            }
	        				else 
	        				{
                                // Create a server object and connect it.
                                wxBusyInfo waiting(wxString::Format(_("Reconnecting to server %s (%s:%d)"),
                                    server->GetDescription().c_str(), server->GetName().c_str(), server->GetPort()), this);

                                // Give the UI a chance to redraw
                                wxSafeYield();
                                wxMilliSleep(100);
                                wxSafeYield();

	        					if (!server->connection()->Reconnect())
                                {
                                    server->Disconnect(this);
                                    browser->SelectItem(serverItem);
                                    execSelChange(serverItem, true);
                                    browser->DeleteChildren(serverItem);
                                }
                                else
                                    // Indicate things are back to normal
                                    userInformed = false;
	        				}
                        }
                    }
                }

                serverItem = browser->GetNextChild(serversObj->GetId(), cookie);
            }
        }
        folderitem = browser->GetNextChild(browser->GetRootItem(), foldercookie);
    }
    return userInformed;
}
Beispiel #12
0
static void makemoves(void) {
	int i, hitme;
	char ch;
	while (TRUE) { /* command loop */
		hitme = FALSE;
		justin = 0;
		Time = 0.0;
		i = -1;
		while (TRUE)  { /* get a command */
			chew();
			skip(1);
			proutn("COMMAND> ");
			if (scan() == IHEOL) continue;
			for (i=0; i < 29; i++) // Abbreviations allowed for the first 29 commands, only.
				if (isit(commands[i]))
					break;
			if (i < 29) break;
			for (; i < NUMCOMMANDS; i++)
				if (strcmp(commands[i], citem) == 0) break;
			if (i < NUMCOMMANDS
#ifndef CLOAKING
			    && i != 26 // ignore the CLOAK command
#endif
#ifndef CAPTURE
			    && i != 27 // ignore the CAPTURE command
#endif
#ifndef SCORE
			    && i != 28 // ignore the SCORE command
#endif
#ifndef DEBUG
			    && i != 33 // ignore the DEBUG command
#endif
			   ) break;

			if (skill <= SFAIR)  {
				prout("UNRECOGNIZED COMMAND. LEGAL COMMANDS ARE:");
				listCommands(TRUE);
			}
			else prout("UNRECOGNIZED COMMAND.");
		}
		switch (i) { /* command switch */
			case 0:			// srscan
				srscan(1);
				break;
			case 1:			// lrscan
				lrscan();
				break;
			case 2:			// phasers
				phasers();
                if (ididit) {
#ifdef CLOAKING
                    if (irhere && d.date >= ALGERON && !isviolreported && iscloaked) {
                        prout("The Romulan ship discovers you are breaking the Treaty of Algeron!");
                        ncviol++;
                        isviolreported = TRUE;
                    }
#endif
                    hitme = TRUE;
                }
				break;
			case 3:			// photons
				photon();
                if (ididit) {
#ifdef CLOAKING
                    if (irhere && d.date >= ALGERON && !isviolreported && iscloaked) {
                        prout("The Romulan ship discovers you are breaking the Treaty of Algeron!");
                        ncviol++;
                        isviolreported = TRUE;
                    }
#endif
                    hitme = TRUE;
                }
				break;
			case 4:			// move
				warp(1);
				break;
			case 5:			// shields
				sheild(1);
				if (ididit) {
					attack(2);
					shldchg = 0;
				}
				break;
			case 6:			// dock
				dock();
				break;
			case 7:			// damages
				dreprt();
				break;
			case 8:			// chart
				chart(0);
				break;
			case 9:			// impulse
				impuls();
				break;
			case 10:		// rest
				waiting();
				if (ididit) hitme = TRUE;
				break;
			case 11:		// warp
				setwrp();
				break;
			case 12:		// status
				srscan(3);
				break;
			case 13:			// sensors
				sensor();
				break;
			case 14:			// orbit
				orbit();
				if (ididit) hitme = TRUE;
				break;
			case 15:			// transport "beam"
				beam();
				break;
			case 16:			// mine
				mine();
				if (ididit) hitme = TRUE;
				break;
			case 17:			// crystals
				usecrystals();
				break;
			case 18:			// shuttle
				shuttle();
				if (ididit) hitme = TRUE;
				break;
			case 19:			// Planet list
				preport();
				break;
			case 20:			// Status information
				srscan(2);
				break;
			case 21:			// Game Report 
				report(0);
				break;
			case 22:			// use COMPUTER!
				eta();
				break;
			case 23:
				listCommands(TRUE);
				break;
			case 24:		// Emergency exit
				clearscreen();	// Hide screen
				freeze(TRUE);	// forced save
				exit(1);		// And quick exit
				break;
			case 25:
				probe();		// Launch probe
				break;
#ifdef CLOAKING
			case 26:
				cloak();        // turn on/off cloaking
				if (iscloaking) {
					attack(2); // We will be seen while we cloak
					iscloaking = FALSE;
					iscloaked = TRUE;
				}
				break;
#endif
#ifdef CAPTURE
			case 27:
				capture();      // Attempt to get Klingon ship to surrender
				if (ididit) hitme = TRUE;
				break;
#endif
#ifdef SCORE
			case 28:
				score(1);    // get the score
				break;
#endif
			case 29:			// Abandon Ship
				abandn();
				break;
			case 30:			// Self Destruct
				dstrct();
				break;
			case 31:			// Save Game
				freeze(FALSE);
				if (skill > SGOOD)
					prout("WARNING--Frozen games produce no plaques!");
				break;
			case 32:			// Try a desparation measure
				deathray();
				if (ididit) hitme = TRUE;
				break;
#ifdef DEBUG
			case 33:			// What do we want for debug???
				debugme();
				break;
#endif
			case 34:		// Call for help
				help();
				break;
			case 35:
				alldone = 1;	// quit the game
#ifdef DEBUG
				if (idebug) score(0);
#endif
				break;
			case 36:
				helpme();	// get help
				break;
		}
		for (;;) {
			if (alldone) break;		// Game has ended
#ifdef DEBUG
			if (idebug) prout("2500");
#endif
			if (Time != 0.0) {
				events();
				if (alldone) break;		// Events did us in
			}
			if (d.galaxy[quadx][quady] == 1000) { // Galaxy went Nova!
				atover(0);
				continue;
			}
			if (nenhere == 0) movetho();
			if (hitme && justin==0) {
				attack(2);
				if (alldone) break;
				if (d.galaxy[quadx][quady] == 1000) {	// went NOVA! 
					atover(0);
					hitme = TRUE;
					continue;
				}
			}
			break;
		}
		if (alldone) break;
	}
}
Beispiel #13
0
int
dotest(void)
{
	CLIENT *client, *mountclient;
	AUTH *auth;
	struct timeval timeout;
	caddr_t args, res;
	enum clnt_stat status;
	rpcproc_t proc;
	call3_test_t *test;
	void *argbuf = NULL;
	void *resbuf = NULL;
	struct mountres3 mountres3;
	char *sp;
	volatile int a = 0;

	while (waiting(&a) == 0)
		continue;

	timeout.tv_sec = 30;
	timeout.tv_usec = 0;

	mountclient = clnt_create("localhost", MOUNTPROG, MOUNTVERS3, "tcp");
	if (mountclient == NULL) {
		clnt_pcreateerror("clnt_create mount");
		return (1);
	}
	auth = authsys_create_default();
	mountclient->cl_auth = auth;
	sp = sharedpath;
	bzero(&mountres3, sizeof (mountres3));
	status = clnt_call(mountclient, MOUNTPROC_MNT,
	    xdr_dirpath, (char *)&sp,
	    xdr_mountres3, (char *)&mountres3,
	    timeout);
	if (status != RPC_SUCCESS) {
		clnt_perror(mountclient, "mnt");
		return (1);
	}
	if (mountres3.fhs_status != 0) {
		fprintf(stderr, "MOUNTPROG/MOUNTVERS3 failed %d\n",
		    mountres3.fhs_status);
		return (1);
	}
	rootfh = &mountres3.mountres3_u.mountinfo.fhandle;

	client = clnt_create("localhost", NFS3_PROGRAM, NFS_V3, "tcp");
	if (client == NULL) {
		clnt_pcreateerror("clnt_create");
		return (1);
	}
	client->cl_auth = auth;

	for (test = call3_tests; test->arginit; ++test) {
		argbuf = realloc(argbuf, test->argsize);
		resbuf = realloc(resbuf, test->ressize);
		if ((argbuf == NULL) || (resbuf == NULL)) {
			perror("realloc() failed");
			return (1);
		}
		(test->arginit)(argbuf);
		bzero(resbuf, test->ressize);
		status = clnt_call(client, test->proc,
		    test->xdrargs, argbuf,
		    test->xdrres, resbuf,
		    timeout);
		if (status != RPC_SUCCESS)
			clnt_perror(client, "call");
	}

	status = clnt_call(mountclient, MOUNTPROC_UMNT,
	    xdr_dirpath, (char *)&sp,
	    xdr_void, NULL,
	    timeout);
	if (status != RPC_SUCCESS)
		clnt_perror(mountclient, "umnt");

	return (0);
}
Beispiel #14
0
int screen_3::Run(sf::RenderWindow &App) {
    Cursor mouse_cursor(App,resources->textures.get("MouseCursor"));

    sf::Sprite mock_cursor;
    mock_cursor.setTexture(resources->textures.get("MockCursor"));

    sf::Sprite background;
    background.setTexture(resources->textures.get("GameBackground"));

    bool Running = true;
    int starting_index = resources->start_index;
    Sidebar sidebar(App, resources);

    sf::Clock clock;

    Board board(starting_index,App, resources);
    board.move(0,50);
    board.animateMovement(sf::Vector2f(200,50),3);
    Replay replay(App, resources);

    Player* player1 (new Player(board.getBoardGrid(),'X'));
    Player* player2 (new Player(board.getBoardGrid(),'O'));
    Player* curr_player;
    player1->setTexture(&resources->textures.get("Player1Mark"));
    player2->setTexture(&resources->textures.get("Player2Mark"));

    Button waiting(App);
    waiting.load(resources->textures.get("WaitingBase"),resources->textures.get("WaitingHover"));
    //waiting.setScale(0.7);
    waiting.setPosition((App.getSize().x-waiting.getGlobalBounds().x)/2+40,App.getSize().y-waiting.getGlobalBounds().y+5);
    VictoryBanner victory_banner(App,player1,player2,replay, resources);
    Messenger messenger(App, resources);
    PauseOverlay pause_screen(App, resources, true);
    while (Running)
    {
        sf::Event event;

        while (App.pollEvent(event))
        {

            if(messageSocket->receive(packet) == sf::Socket::Disconnected)
            {
                sidebar.stopMusic();
                pause_screen.setString("    DISCONNECTED");
                pause_screen.isDisconnected(true);
                pause_screen.setPaused(true);
            }
            else    {
                board.handleEvents(event);             //if not disconnected
                if(sidebar.updateEvents(event))
                    pause_screen.setPaused(true);
            }
            if(pause_screen.updateEvent(event))
            {
               return pause_screen.getActionKeyCode();
            }
            messenger.updateEvents(event);
            if (event.type == sf::Event::Closed)
            {
                return (-1);
            }
            if(victory_banner.handleEvents(event))
            {
                return victory_banner.getActionKeyCode();
            }
        }
        board.updateAnimation();
        messenger.update(messageSocket);
        if((is_host&&player_turn) || (!is_host && !player_turn)) {
            curr_player = player1;
        }
        else {
            curr_player = player2;
        }
        mouse_cursor.update();
        replay.record(player_turn , replaySocket);
        mock_cursor.setPosition(replay.getCurrPosition());
        if(!board.game_done)
            {
                 if(sidebar.checkTimer(resources->isTimerActivated,resources->turn_timer))   {
                    if(player_turn) {
                        is_waiting = false;
                        board.update(curr_player,is_host,socket);
                    }
                    else{
                        is_waiting = true;
                        board.update(curr_player,socket);  //receiver
                    }
                    if(board.round_done)    {
                        sidebar.restartClock();
                        player_turn = !player_turn;
                        board.round_done = false;
                    }
                }
                else    {
                    player_turn = !player_turn;
                    sidebar.restartClock();
                }
            }

            else    {
                replay.save();
                sidebar.stopMusic();
                victory_banner. displayBanner(is_host);
            }
        App.clear();
        App.draw(background);
        App.draw(board);
        if(!player_turn)
            App.draw(mock_cursor);
        if(is_waiting)
            App.draw(waiting);
        App.draw(sidebar);
        if(board.game_done)    {
            App.draw(victory_banner);
        }
        if(pause_screen.isPaused())    {
            App.draw(pause_screen);
        }
        App.draw(messenger);

        App.draw(mouse_cursor);
        App.display();
    }
    return (-1);
}
Beispiel #15
0
 bool good() const
 {
     return !empty() && !exited() && !waiting();
 }
Beispiel #16
0
int
main(int argc, char **argv)
{
	char line[BUFSIZ];
	char *lyric;
	char *ttag;			/* timing tag	*/
	char *tag, *tag_value;
	struct lrc_info lrc_info = LRC_INFO_NULL;
	useconds_t wtime = 0;		/* waiting time	*/
	useconds_t time_sum = 0;

	if (argc < 2)
		usage();
	
	FILE *fh = fopen(argv[1], "r");

	if (fh == NULL)
		return EXIT_FAILURE;

	while (fgets(line, BUFSIZ, fh)) {
		/* check for none conforming lines */
		if (line[0] != '[' || strnlen(line, BUFSIZ) < 5)
			continue;

		if (isdigit(line[1]))	/* check for first lyric line */
			break;

		tag = line + 1;
		char *tag_separator = strchr(line, ':');
		if (tag_separator != NULL) {
			*tag_separator = '\0';
			tag_value = tag_separator + 1;

			char *tag_end = strchr(tag_value, ']');
			*tag_end = '\0';

			set_lrc_info(&lrc_info, tag, tag_value);
		}
	}

	do {
		if (line[0] != '[')	/* check for empty lines */
			continue;

		/* search for begin of lyric */
		if ((lyric = strchr(line, ']')) == NULL)
			continue;
		lyric++;

		wtime = str2time(line);
		time_sum = waiting(wtime, time_sum);

		while ((ttag = strchr(lyric, '<')) != NULL) {
			fwrite(lyric, sizeof *lyric, ttag - lyric, stdout);
			fflush(stdout);

			wtime = str2time(ttag);
			time_sum = waiting(wtime, time_sum);

			/* search for begin of lyric */
			if ((lyric = strchr(ttag, '>')) == NULL)
				continue;
			lyric++;
		}

		printf("%s", lyric);
		fflush(stdout);
	} while (fgets(line, BUFSIZ, fh));

	fclose(fh);

	waiting(lrc_info.length, time_sum);	/* wait for end of the song */

	return EXIT_SUCCESS;
}
Beispiel #17
0
	bool signal() {
		AcquireSRWLockExclusive( &lock );
		if( waiting() ) WakeAllConditionVariable( &condition );
		ReleaseSRWLockExclusive( &lock );
		return true;
	}
Beispiel #18
0
void spawn_job(job_t *j, bool fg) 
{

  pid_t pid;
  process_t *p;
  int countProcess = 0;
  int loopCounter = -1;
  int i;


  //count number of processes in the job
  for(p = j->first_process; p; p = p->next)
  {
    countProcess++;
  } 

  //printf("count process: %d \n", countProcess);

  int pipefd[countProcess-1][2]; //initialize 2-dimensional array [number of process][input/output]
  //printf("test");

  //open all pipes
  if(countProcess > 1)
  {
    for(i = 0; i < (countProcess-1); i++)
    {
      //printf("piped %d \n", i);
      pipe(pipefd[i]);
    }
  }


  for(p = j->first_process; p; p = p->next) {

	  /* YOUR CODE HERE? */
	  /* Builtin commands are already taken care earlier */
 
    loopCounter++;

    switch (pid = fork()) {
      // int status;

      case -1: /* fork failure */
        perror("fork");
        exit(EXIT_FAILURE);

      case 0: /* child process  */
        p->pid = getpid();	    
        new_child(j, p, fg);

	    /* YOUR CODE HERE?  Child-side code for new process. */

        if (p->ifile != NULL)
        {
          int fd = open(p->ifile, O_RDONLY);
          dup2(fd, STDIN_FILENO);
        }

        if (p->ofile != NULL)
        {
          int fd = open(p->ofile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
          dup2(fd, STDOUT_FILENO);
        }

        //pipe
        if(countProcess > 1)
        {
          //printf("begin piping \n");
          //first process is output        

          //need to loop through number of process and close all pipes
          if(p == j->first_process)
          {

            dup2(pipefd[loopCounter][1], 1); //duplicate output as output for next process 
            closePipe(pipefd, countProcess);

          }  

          //last process
          else if (p->next == NULL)
          {
            dup2(pipefd[loopCounter-1][0], 0);
            closePipe(pipefd, countProcess);

          }

          //for middle: dup both input and output
          
          else
          {
            dup2(pipefd[loopCounter][1], 1);
            dup2(pipefd[loopCounter-1][0], 0);

            closePipe(pipefd, countProcess);


          }

        }

        printf("%d (Launched): %s\n", j->pgid, j->commandinfo);

        execvp(p->argv[0], p->argv);
        perror("New child should have done an exec");
        exit(EXIT_FAILURE);  /* NOT REACHED */
        break;    /* NOT REACHED */

      default: /* parent */
        /* establish child process group */
        p->pid = pid;
        set_child_pgid(j, p);

        /* YOUR CODE HERE?  Parent-side code for new process.  */


        if (p->next == NULL) //if last process
        {
          process_t *p2;

          p2 = j->first_process;
          while(p2 != NULL)
          {
            //printf("waiting for process \n");

            //if fg true waiting, else bg stuff

            if(fg == true)
            {
              waiting(p2);
            }
            else
            {
              struct sigaction action;
              action.sa_sigaction = sighandler;

              sigfillset(&action.sa_mask);
              action.sa_flags = SA_SIGINFO;
              sigaction(SIGCHLD, &action, NULL);
            }
            
            closePipe(pipefd, countProcess);


            p2 = p2->next;
          }
        }

        //wait for child to finish
    }

    /* YOUR CODE HERE?  Parent-side code for new job.*/
    //printf("assign terminal back to dsh\n");
	  seize_tty(getpid()); // assign the terminal back to dsh

  }
}
	void timer::again_if()
	{
		if (!waiting())
			again();
	}
Beispiel #20
0
Datei: sst.c Projekt: aichao/sst
static void makemoves(void) {
	int i, hitme;
	char ch;
	while (TRUE) { /* command loop */
		hitme = FALSE;
		justin = 0;
		Time = 0.0;
		i = -1;
		while (TRUE)  { /* get a command */
			chew();
			skip(1);
			proutn("COMMAND> ");
      // Use of scan() here (after chew) will get a new line of input
      // and will return IHEOL iff new line of input contains nothing
      // or a numeric input is detected but conversion fails.
			if (scan() == IHEOL) continue;
			for (i=0; i < 26; i++)
				if (isit(commands[i]))
					break;
			if (i < 26) break;
			for (; i < NUMCOMMANDS; i++)
				if (strcmp(commands[i], citem) == 0) break;
			if (i < NUMCOMMANDS) break;
      // we get here iff the first parsed input from the line does not 
      // match one of the commands. In this case, the rest of the line
      // is discarded, the below message is printed, and we go back to 
      // get a new command.
			if (skill <= 2)  {
				prout("UNRECOGNIZED COMMAND. LEGAL COMMANDS ARE:");
				listCommands(TRUE);
			}
			else prout("UNRECOGNIZED COMMAND.");
		} // end get command loop
    // we get here iff the first parsed input from the line matches one
    // of the commands (i.e., command i). We use i to dispatch the 
    // handling of the command. The line may still contain additional
    // inputs (i.e., parameters of the command) that is to be parsed by
    // the dispatched command handler. If the line does not contain
    // all the necessary parameters, the dispatched command handler is 
    // responsible to get additional input(s) interactively using scan().
    // The dispatched command handler is also responsible to handle any 
    // input errors.
		switch (i) { /* command switch */
			case 0:			// srscan
				srscan(1);
				break;
			case 1:			// lrscan
				lrscan();
				break;
			case 2:			// phasers
				phasers();
				if (ididit) hitme = TRUE;
				break;
			case 3:			// photons
				photon();
				if (ididit) hitme = TRUE;
				break;
			case 4:			// move
				warp(1);
				break;
			case 5:			// shields
				sheild(1);
				if (ididit) {
					attack(2);
					shldchg = 0;
				}
				break;
			case 6:			// dock
				dock();
				break;
			case 7:			// damages
				dreprt();
				break;
			case 8:			// chart
				chart(0);
				break;
			case 9:			// impulse
				impuls();
				break;
			case 10:		// rest
				waiting();
				if (ididit) hitme = TRUE;
				break;
			case 11:		// warp
				setwrp();
				break;
			case 12:		// status
				srscan(3);
				break;
			case 13:			// sensors
				sensor();
				break;
			case 14:			// orbit
				orbit();
				if (ididit) hitme = TRUE;
				break;
			case 15:			// transport "beam"
				beam();
				break;
			case 16:			// mine
				mine();
				if (ididit) hitme = TRUE;
				break;
			case 17:			// crystals
				usecrystals();
				break;
			case 18:			// shuttle
				shuttle();
				if (ididit) hitme = TRUE;
				break;
			case 19:			// Planet list
				preport();
				break;
			case 20:			// Status information
				srscan(2);
				break;
			case 21:			// Game Report 
				report(0);
				break;
			case 22:			// use COMPUTER!
				eta();
				break;
			case 23:
				listCommands(TRUE);
				break;
			case 24:		// Emergency exit
				clearscreen();	// Hide screen
				freeze(TRUE);	// forced save
				exit(1);		// And quick exit
				break;
			case 25:
				probe();		// Launch probe
				break;
			case 26:			// Abandon Ship
				abandn();
				break;
			case 27:			// Self Destruct
				dstrct();
				break;
			case 28:			// Save Game
				freeze(FALSE);
				if (skill > 3)
					prout("WARNING--Frozen games produce no plaques!");
				break;
			case 29:			// Try a desparation measure
				deathray();
				if (ididit) hitme = TRUE;
				break;
			case 30:			// What do we want for debug???
#ifdef DEBUG
				debugme();
#endif
				break;
			case 31:		// Call for help
				help();
				break;
			case 32:
				alldone = 1;	// quit the game
#ifdef DEBUG
				if (idebug) score();
#endif
				break;
			case 33:
				helpme();	// get help
				break;
		} // end command switch
		for (;;) {
			if (alldone) break;		// Game has ended
#ifdef DEBUG
			if (idebug) prout("2500");
#endif
			if (Time != 0.0) {
				events();
				if (alldone) break;		// Events did us in
			}
			if (d.galaxy[quadx][quady] == 1000) { // Galaxy went Nova!
				atover(0);
				continue;
			}
			if (nenhere == 0) movetho();
			if (hitme && justin==0) {
				attack(2);
				if (alldone) break;
				if (d.galaxy[quadx][quady] == 1000) {	// went NOVA! 
					atover(0);
					hitme = TRUE;
					continue;
				}
			}
			break;
		} // end event loop
		if (alldone) break;
	} // end command loop
}
Beispiel #21
0
int connect_host(/*int m, short event, void* arg*/)
{
	char ipaddr[30];
	char port[10];
	//free(arg);
	readcfg("ctosport",port);
	readcfg("ip",ipaddr);
	static int sec = 2;
	int sock = false;

	static int times_beatheart = 0;
	static int times_regist = 0;

DNS_label:
	if(dnsbyping(ipaddr) == false )
	{
		printf("dns fail");
		goto sleep_label;
	}

socket_label:
	if(	(sock = begin(ipaddr,port)) == false )
	{	
		printf("scoket fail");
		goto sleep_label;	
	}

checkcfg_label:
	if(extid == 0)
		goto regist_label;
	else
		goto beatheart_label;

regist_label:
	if(rgist(sock) == false)
	{
		printf("rgist fail");
		if(times_regist < 5)
		{
			times_regist++;
			sleep(5);
			goto socket_label;
		}
		else
		{
			times_regist = 0;
			goto sleep_label;
		}
	}

beatheart_label:
	if(beatheart(sock) == false)
	{
		printf("heart fail");
		if(times_beatheart < 5)
		{
			times_beatheart++;
			sleep(5);
			goto socket_label;
		}
		else
		{
			times_beatheart = 0;
			goto regist_label;		
		}
	}

waiting_label:
	sec = 2;
	if(waiting(sock) == false)
	{
		printf("task fail");
		goto sleep_label;			
	}

sleep_label:
	if(sock != false)
	{
		close(false);
		sock = false;
	}
	sec = 2;
	if(sec > 3600*24)
		sec = 3600*24;
	//Timer(sec,connect_host,NULL);
	printf("%d\n", sec);
	return sec;
}
Beispiel #22
0
int main(void) {
  // Helpful Flags
  bool IS_NOT_ALONE, IS_ALONE, IS_INTERNAL, IS_EXTERNAL, IS_CD, IS_EXIT;
  bool IS_PARENT, IS_CHILD, IS_REDIRECTED, IS_FIRST, IS_LAST, IS_MIDDLE;

  // Pipe Holders
  int *pipe_left;
  int *pipe_right;   
  
  // Holders for dup'd STDIN, OUT in case of redirected internal commands
  int ORIGINAL_STDIN, ORIGINAL_STDOUT; 

  // Holder for command string from STDIO.
  char *str;
  
  // This gets the current username
  char *login;
  login = getlogin();

  // This is the current working directory
  // This will be updated on cd commands run internally
  char cwd[MAXPATH];
  getcwd(cwd, MAXPATH);
  
  // pointer to pid holder for children and waiting
  pid_t child_pid; 

  // for execution & internal/external checking
  char *command_name;

  size_t command_length;

  // parsed command holder + pointer for counting number of commands
  command *comms = NULL;
  command *command_walker;

  char prompt[80];

  // for loop iteration variable
  int i;

  // This will never be freed until we exit (and then by default).
  pipe_left = malloc(2*sizeof(int));
  pipe_right = malloc(2*sizeof(int));
  if ((pipe_left == NULL) || (pipe_right == NULL)) {
    fprintf(stderr, 
      "%s: Could not allocate holder for potential pipes. Exiting.\n", 
      SHELL_ERROR_IDENTIFIER);
    exit(EXIT_FAILURE);
  }
  
  /**
    * Curiosity Shell Control Flow
    * The structure of the program is broken up as follows:
    * Pipe Creation
    * Fork Handler
    * Pipe Cleanup
    * Redirection (Including for Parent Internal Commands)
    * Command Run (Child, Parent), Parent Wait (if appropriate)
    * Reset Temporary Parent Redirection for Internal Commands
    * Get Next User Input
    */
  while(1){
    // Free the previous command
    free_commands(comms);

    // Display prompt.
    sprintf(prompt, "%s:%s> ", login, cwd);
    str = readline(prompt);
    if (str == NULL) {
      exit(EXIT_SUCCESS);
    }
    
    // Save the history.
    if (str && *str)
      add_history (str);    
      
    // Prepare to tokenize    
    command_length = strlen((const char *) str);
    if (command_length == 0) {
      comms = NULL;
      continue;
    }

    // Tokenize & parse into discrete commands
    comms = get_commands(str);
    if (str != NULL)
      free(str);
    
    // If no commands, create another prompt in the next iteration
    if (comms == NULL) {
      continue;
    }

    // count number of commands, command_length
    command_length = 0;
    command_walker = comms;
    while (command_walker->argv != NULL) {
      command_length += 1;
      command_walker += 1;
    }
    
    // Set IS_ALONE, IS_NOT_ALONE Flags
    IS_ALONE = false;
    IS_NOT_ALONE = false;
    if (command_length == 1) IS_ALONE = true;
    if (command_length > 1) IS_NOT_ALONE = true;

    /* Handle Latest Set of Commands */
    for (i = 0; i < command_length; i++) {
      /*
        Set Flags for THIS command
        IS_FIRST, IS_MIDDLE, IS_LAST, IS_INTERNAL, IS_EXTERNAL, IS_CD, IS_EXIT
      */
      
      command_name = comms[i].argv[0];        

      IS_FIRST = false;
      IS_MIDDLE = false;
      IS_LAST = false;

      if (i == 0) {
        IS_FIRST = true;
      }
      if (i == (command_length-1)) {
        IS_LAST = true;
      }
      if ((!IS_FIRST) && (!IS_LAST)) {
        IS_MIDDLE = true;
      }

      IS_INTERNAL = false;
      IS_EXTERNAL = true;
      IS_CD = false;
      IS_EXIT = false;
      if (strcmp((const char *)command_name, (const char *) "cd") == 0) {
        IS_CD = true;
      }
      if (strcmp((const char *)command_name, (const char *) "exit") == 0) {
        IS_EXIT = true;
      }
      if (IS_CD || IS_EXIT) {
        IS_INTERNAL = true;
      }
      if (IS_INTERNAL) {
        IS_EXTERNAL = false;
      } 
      /*
        Pipe & Fork Handler (fork_yourself), 
        Set IS_PARENT, IS_CHILD in fork_yourself, and use its return value to 
        determine error
      */

      if (IS_FIRST && IS_ALONE) {
        // No piping        
        
        // Fork and set IS_PARENT, IS_CHILD
        if (!fork_yourself(IS_INTERNAL, IS_ALONE, &IS_PARENT, &IS_CHILD, 
          &child_pid)) { 
          break; 
        }

        // No pipe handling

      } else if (IS_FIRST && IS_NOT_ALONE) {
        // pipe to pipe_right, check for pipe errors & return to prompt 
        // if errors found.
        if (!pipe_creation_handler(&pipe_left, &pipe_right, 1)) {
          fprintf(stderr, "%s: Right-pipe creation error for command %s.\n", 
            SHELL_ERROR_IDENTIFIER, command_name);
          break;
        }
        
        // Fork and set IS_PARENT, IS_CHILD
        if (!fork_yourself(IS_INTERNAL, IS_ALONE, &IS_PARENT, &IS_CHILD, 
          &child_pid)) { 
          break; 
        }

        // parent closes pipe_right_write
        // errors reported by close are inconsequential
        if (IS_PARENT) {
          close(pipe_right[1]);
        } 
        
        // child closes pipe_right_read
        // child duplicates pipe_right_write to stdout, then closes it.          
        // errors reported by close are inconsequential
        if (IS_CHILD) {
          close(pipe_right[0]);
          if (dup2(pipe_right[1], STDOUT_FILENO) == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            exit(EXIT_FAILURE);
          }
          close(pipe_right[1]);
        }
        
      } else if (IS_LAST && IS_NOT_ALONE) {
        // swap pipe_left/pipe_right
        // no piping        
        pipe_creation_handler(&pipe_left, &pipe_right, 0);                            
        
        // Fork and set IS_PARENT, IS_CHILD        
        if (!fork_yourself(IS_INTERNAL, IS_ALONE, &IS_PARENT, &IS_CHILD, 
          &child_pid)) { 
          break; 
        }

        // parent closees pipe_left_read
        // errors reported by close are inconsequential
        if (IS_PARENT) {
          close(pipe_left[0]);
        }

        // child duplicates pipe_left_read to its stdin, then closes it
        // errors reported by close are inconsequential
        if (IS_CHILD) {
          if (dup2(pipe_left[0], STDIN_FILENO) == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            exit(EXIT_FAILURE);
          }
          close(pipe_left[0]);
        }

      } else if (IS_MIDDLE && IS_NOT_ALONE) {
        // swap pipe_left/pipe_right
        pipe_creation_handler(&pipe_left, &pipe_right, 0);                            
        // pipe to pipe_right, check for pipe errors & return to prompt if 
        // errors found.        
        if (!pipe_creation_handler(&pipe_left, &pipe_right, 1)) {
          fprintf(stderr, "%s: Right-pipe creation error for command %s.\n", 
            SHELL_ERROR_IDENTIFIER, command_name);
          break;
        }        

        // Fork and set IS_PARENT, IS_CHILD
        if (!fork_yourself(IS_INTERNAL, IS_ALONE, &IS_PARENT, &IS_CHILD, 
          &child_pid)) { 
          break; 
        }

        // parent closes pipe_left_read and pipe_right_write
        // errors reported by close are inconsequential
        if (IS_PARENT) {
          close(pipe_left[0]);
          close(pipe_right[1]);
        }

        // child closes pipe_right_read, duplicates pipe_left_read to stdin,
        // pipe_right_write to stdout, then closes both.
        // errors reported by close are inconsequential
        if (IS_CHILD) {
          close(pipe_right[0]);
          if (dup2(pipe_left[0], STDIN_FILENO) == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            exit(EXIT_FAILURE);
          }
          if (dup2(pipe_right[1], STDOUT_FILENO) == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            exit(EXIT_FAILURE);
          }
          close(pipe_left[0]);
          close(pipe_right[1]);
        }

      } else {
        // Unknown case.
        fprintf(stderr, "%s: Unexpected pipe handling case for command %s.\n", 
          SHELL_ERROR_IDENTIFIER, command_name);
        break; 
      }

      /*
        Redirection Handler      
        Set IS_REDIRECTED flag
        Save STDIN/STDOUT/STDERR for later restoration
        This implementation possibly racks up "erroneous file handlers"
        unless dup() removes those on error.
      */       
      IS_REDIRECTED = false;
      if (IS_PARENT && IS_INTERNAL) {        
        if (comms[i].ifile != NULL) {
          IS_REDIRECTED = true;
          ORIGINAL_STDIN = dup(STDIN_FILENO);
          if (ORIGINAL_STDIN == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            break;
          }
        }
        if (comms[i].ofile != NULL) {
          IS_REDIRECTED = true;
          ORIGINAL_STDOUT = dup(STDOUT_FILENO);
          if (ORIGINAL_STDOUT == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            break;
          }
        }
        // Not necessary as we do not handle STDERR redirection
        // ORIGINAL_STDERR = dup(STDERR_FILENO);
        // if (ORIGINAL_STDERR == -1) {
        //   perror(SHELL_ERROR_IDENTIFIER);
        //   break;
        // }        

        if (!redirection(comms[i].ifile, comms[i].ofile, comms[i].append)) {
          break;
        }
      } else if (IS_CHILD) {
        IS_REDIRECTED = true;
        if (!redirection(comms[i].ifile, comms[i].ofile, comms[i].append)) {
          break;
        }
      } 

      /*
        Run/Wait Handler
      */       
      
      if(IS_CHILD && IS_INTERNAL){
      	if(!run_internal(IS_CD, IS_EXIT, cwd, comms[i].argv, comms[i].argc)){
      	  exit(EXIT_FAILURE);
	      }	else{
          exit(EXIT_SUCCESS);
        }
      }

      if(IS_CHILD && IS_EXTERNAL){
	      execute(comms[i].argv);
      }

      if(IS_PARENT && IS_INTERNAL && IS_ALONE){
	      run_internal(IS_CD, IS_EXIT, cwd, comms[i].argv, comms[i].argc);
      }

      if(IS_PARENT && IS_INTERNAL && IS_NOT_ALONE){
	      if(!(waiting(child_pid))){
	       break;
	      }
      }

      if(IS_PARENT && IS_EXTERNAL){
	     if(!(waiting(child_pid))){
	       break;
	     }
      }

      /*
        Parent STDIO Reset
        In case of Single Internal Command with Redirection
      */           
      /*
          On failure, MUST EXIT as user can no longer target STDIN or
          see our STDOUT, possibly.
      */
      if (IS_PARENT && IS_INTERNAL && IS_ALONE && IS_REDIRECTED) {
        if (comms[i].ifile != NULL) {
          if (dup2(ORIGINAL_STDIN, STDIN_FILENO) == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            exit(EXIT_FAILURE);
          }
          close(ORIGINAL_STDIN);
        }
        if (comms[i].ofile != NULL) {
          if (dup2(ORIGINAL_STDOUT, STDOUT_FILENO) == -1) {
            perror(SHELL_ERROR_IDENTIFIER);
            exit(EXIT_FAILURE);
          }
          close(ORIGINAL_STDOUT);
        }
        // Do not need to handle STDERR, we do not support it's redirection
      }

    }
  }
  exit(EXIT_SUCCESS);
}