예제 #1
1
파일: mgquery.c 프로젝트: plbogen/CSDL
void 
search_for_collection (char *name)
{
  char *dir = GetDefEnv ("mgdir", "./");
  char buffer[512];
  struct stat stat_buf;
  if (strrchr (dir, '/') && *(strrchr (dir, '/') + 1) != '\0')
    {
      sprintf (buffer, "%s/", dir);
      SetEnv ("mgdir", buffer, NULL);
      dir = GetEnv ("mgdir");
    }

  sprintf (buffer, "%s.text", name);
  if (stat (buffer, &stat_buf) != -1)
    {
      if ((stat_buf.st_mode & S_IFREG) != 0)
	{
	  /* The name is a directory */
	  SetEnv ("mgname", name, NULL);
	  SetEnv ("mgdir", "./", NULL);
	  return;
	}
    }

  sprintf (buffer, "%s%s", dir, name);
  if (stat (buffer, &stat_buf) != -1)
    {
      if ((stat_buf.st_mode & S_IFDIR) != 0)
	{
	  /* The name is a directory */
	  sprintf (buffer, "%s/%s", name, name);
	  SetEnv ("mgname", buffer, NULL);
	  return;
	}
    }

  /* Look in the current directory last */
  if (stat (name, &stat_buf) != -1)
    {
      if ((stat_buf.st_mode & S_IFDIR) != 0)
	{
	  /* The name is a directory */
	  sprintf (buffer, "%s/%s", name, name);
	  SetEnv ("mgname", buffer, NULL);
	  SetEnv ("mgdir", "./", NULL);
	  return;
	}
    }

  SetEnv ("mgname", name, NULL);
}
예제 #2
0
파일: Game.cpp 프로젝트: medav/RDFT-Project
void Minigame::NewMap() {
	if (NumMoves > 0) {
		SetEnv("difficulty", Engine()->GetInt("difficulty") + rand() % 3 + 1);
		SetEnv("boxsize", 100 - Engine()->GetInt("difficulty"));
		Level++;
	}
	
	int Difficulty = Engine()->GetInt("difficulty");



	NumMoves = 0;

	double Boundary = Engine()->GetDouble("boundary");
	double BoxX, BoxY;
	double BoxSize = Engine()->GetDouble("boxsize");

	Engine()->GetPhysDevice()->Clear();

	// The world!
	ENTITY * WorldTop = new Wall(VectorOf(Engine()->ScreenX() / 2.0, Engine()->ScreenY() + 16), Engine()->ScreenX() + 8, 64);
	ENTITY * WorldBottom = new Wall(VectorOf(Engine()->ScreenX() / 2.0, - 8), Engine()->ScreenX() + 8, 64);
	ENTITY * WorldLeft = new Wall(VectorOf(-16, Engine()->ScreenY() / 2.0), 64, Engine()->ScreenY() + 8);
	ENTITY * WorldRight = new Wall(VectorOf(Engine()->ScreenX() + 16, Engine()->ScreenY() / 2.0), 64, Engine()->ScreenY() + 8);

	Engine()->GetPhysDevice()->AddEntity(WorldTop);
	Engine()->GetPhysDevice()->AddEntity(WorldBottom);
	Engine()->GetPhysDevice()->AddEntity(WorldLeft);
	Engine()->GetPhysDevice()->AddEntity(WorldRight);

	int i;

	ENTITY * Obstruction;
	
	for (i = 0; i < Difficulty; i++) {
		BoxX = rand() % (int)Engine()->ScreenX();
		BoxY = rand() % (int)Engine()->ScreenY();

		if ((BoxX > Boundary || BoxY > Boundary) &&
			(BoxX < Engine()->ScreenX() - Boundary || BoxY < Engine()->ScreenY() - Boundary)) {
			Obstruction = new Wall(VectorOf(BoxX, BoxY), BoxSize, BoxSize);
			Engine()->GetPhysDevice()->AddEntity(Obstruction);
		}
		else 
			i--;
	}

	hole = new Hole(VectorOf(Engine()->ScreenX() - 100, Engine()->ScreenY() - 100));
	Engine()->GetPhysDevice()->AddEntity(hole);

	ball = new Ball(VectorOf(50, 80));
	Engine()->GetPhysDevice()->AddEntity(ball);
}
예제 #3
0
파일: Game.cpp 프로젝트: medav/RDFT-Project
// Set up the default env values
void SetupEnv() {
	SetEnv("friction", "0.03");
	SetEnv("cc", "0.95");
	SetEnv("ball_tex", "ball");
	SetEnv("bg_tex", "background");
	SetEnv("wall_tex", "block");
	SetEnv("hole_tex", "hole");
	SetEnv("time_mul", "0.25");
	SetEnv("boundary", "200");
	SetEnv("boxsize", "100");
	SetEnv("difficulty", "1");
}
예제 #4
0
bool
Env::SetEnvWithErrorMessage( const char *nameValueExpr, MyString *error_msg )
{
	char *expr, *delim;
	int retval;

	if( nameValueExpr == NULL || nameValueExpr[0] == '\0' ) {
		return false;
	}

	// make a copy of nameValueExpr for modifying
	expr = strnewp( nameValueExpr );
	ASSERT( expr );

	// find the delimiter
	delim = strchr( expr, '=' );

	if(delim == NULL && strstr(expr,"$$")) {
		// This environment entry is an unexpanded $$() macro.
		// We just want to keep it in the environment verbatim.
		SetEnv(expr,NO_ENVIRONMENT_VALUE);
		delete[] expr;
		return true;
	}

	// fail if either name or delim is missing
	if( expr == delim || delim == NULL ) {
		if(error_msg) {
			MyString msg;
			if(delim == NULL) {
				msg.sprintf(
				  "ERROR: Missing '=' after environment variable '%s'.",
				  nameValueExpr);
			}
			else {
				msg.sprintf("ERROR: missing variable in '%s'.",expr);
			}
			AddErrorMessage(msg.Value(),error_msg);
		}
		delete[] expr;
		return false;
	}

	// overwrite delim with '\0' so we have two valid strings
	*delim = '\0';

	// do the deed
	retval = SetEnv( expr, delim + 1 );
	delete[] expr;
	return retval;
}
예제 #5
0
bool
Env::SetEnv( const char* var, const char* val )
{
	MyString myVar = var;
	MyString myVal = val;
	return SetEnv( myVar, myVal );
}
예제 #6
0
void
Env::Import( void )
{
	char **my_environ = GetEnviron();
	for (int i=0; my_environ[i]; i++) {
		const char	*p = my_environ[i];

		int			j;
		MyString	varname = "";
		MyString	value = "";
		for (j=0;  ( p[j] != '\0' ) && ( p[j] != '=' );  j++) {
			varname += p[j];
		}
		if ( p[j] == '\0' ) {
				// ignore entries in the environment that do not
				// contain an assignment
			continue;
		}
		if ( varname.IsEmpty() ) {
				// ignore entries in the environment that contain
				// an empty variable name
			continue;
		}
		ASSERT( p[j] == '=' );
		value = p+j+1;

		// Allow the application to filter the import
		if ( ImportFilter( varname, value ) ) {
			bool ret = SetEnv( varname, value );
			ASSERT( ret ); // should never fail
		}
	}
}
예제 #7
0
void
main_pre_dc_init( int, char*[] )
{
	DC_Skip_Auth_Init();
	DC_Skip_Core_Init();
#ifdef WIN32
	_setmaxstdio(2048);
#endif

		// Convert the DAGMan log file name to an absolute path if it's
		// not one already, so that we'll log things to the right file
		// if we change to a different directory.
	const char *	logFile = GetEnv( "_CONDOR_DAGMAN_LOG" );
	if ( logFile && !fullpath( logFile ) ) {
		MyString	currentDir;
		if ( condor_getcwd( currentDir ) ) {
			MyString newLogFile(currentDir);
			newLogFile += DIR_DELIM_STRING;
			newLogFile += logFile;
			SetEnv( "_CONDOR_DAGMAN_LOG", newLogFile.Value() );
		} else {
			debug_printf( DEBUG_NORMAL, "ERROR: unable to get cwd: %d, %s\n",
					errno, strerror(errno) );
		}
	}
}
예제 #8
0
static void RunJob(const char *user, CronLine *line)
{
	struct passwd *pas;
	pid_t pid;

	/* prepare things before vfork */
	pas = getpwnam(user);
	if (!pas) {
		crondlog(LVL9 "can't get uid for %s", user);
		goto err;
	}
	SetEnv(pas);

	/* fork as the user in question and run program */
	pid = vfork();
	if (pid == 0) {
		/* CHILD */
		/* change running state to the user in question */
		ChangeUser(pas);
		if (DebugOpt) {
			crondlog(LVL5 "child running %s", DEFAULT_SHELL);
		}
		execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL);
		crondlog(ERR20 "can't exec, user %s cmd %s %s %s", user,
				 DEFAULT_SHELL, "-c", line->cl_Shell);
		_exit(EXIT_SUCCESS);
	}
	if (pid < 0) {
		/* FORK FAILED */
		crondlog(ERR20 "can't vfork");
 err:
		pid = 0;
	}
	line->cl_Pid = pid;
}
예제 #9
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_cdpath(void)
{
    if (cdpath == 0)
	SetEnv(&cdpath, DftEnv("CDPATH", ""));
    return cdpath;
}
예제 #10
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_directory(void)
{
    if (directory == 0)
	SetEnv(&directory, DftEnv("TMP", P_tmpdir));
    return directory;
}
예제 #11
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_xdisplay(void)
{
    if (x_display == 0)
	SetEnv(&x_display, DftEnv("DISPLAY", x_get_display_name()));
    return x_display;
}
예제 #12
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_xshellflags(void)
{
    if (x_shellflags == 0)
	SetEnv(&x_shellflags, DftEnv("XSHELLFLAGS", DEFAULT_XSHELLFLAGS));
    return x_shellflags;
}
예제 #13
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_xshell(void)
{
    if (x_shell == 0)
	SetEnv(&x_shell, DftEnv("XSHELL", DEFAULT_XSHELL));
    return x_shell;
}
예제 #14
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_findpath(void)
{
    if (findpath == 0)
	SetEnv(&findpath, DftEnv("VILE_FINDPATH", ""));
    return (findpath);
}
예제 #15
0
파일: statevar.c 프로젝트: ricksladkey/vile
char *
get_shell(void)
{
    if (shell == 0)
	SetEnv(&shell, DftEnv(SHELL_NAME, SHELL_PATH));
    return shell;
}
예제 #16
0
void
Env::MergeFrom( Env const &env )
{
	MyString var,val;

	env._envTable->startIterations();
	while(env._envTable->iterate(var,val)) {
		ASSERT(SetEnv(var,val));
	}
}
예제 #17
0
/**
 * \brief set the global variables
 */
void testSetEnvNormal()
{
  strcpy(Source, "38 - http://www.fossology.org/testdata/wgetagent/mkpackages -l 1 -R index.html*");
  strcpy(TempFileDir, "./test_result");
  SetEnv(Source, TempFileDir);
  CU_ASSERT_EQUAL(GlobalUploadKey, 38);
  char *cptr = strstr(GlobalTempFile, "./test_result/wget."); /* is like ./test_result/wget.29923 */
  CU_ASSERT_PTR_NOT_NULL(cptr);
  CU_ASSERT_STRING_EQUAL(GlobalURL, "http://www.fossology.org/testdata/wgetagent/mkpackages");
  CU_ASSERT_STRING_EQUAL(GlobalParam, "-l 1 -R index.html*");
}
예제 #18
0
void
VMUniverseMgr::killVM(const char *matchstring)
{
	if ( !matchstring ) {
		return;
	}
	if( !m_vm_type.Length() || !m_vmgahp_server.Length() ) {
		return;
	}

	// vmgahp is daemonCore, so we need to add -f -t options of daemonCore.
	// Then, try to execute vmgahp with 
	// vmtype <vmtype> match <string>"
	ArgList systemcmd;
	systemcmd.AppendArg(m_vmgahp_server);
	systemcmd.AppendArg("-f");
	char *gahp_log_file = param("VM_GAHP_LOG");
	if( gahp_log_file ) {
		free(gahp_log_file);
	}else {
		systemcmd.AppendArg("-t");
	}
	systemcmd.AppendArg("-M");
	systemcmd.AppendArg(VMGAHP_KILL_MODE);
	systemcmd.AppendArg("vmtype");
	systemcmd.AppendArg(m_vm_type);
	systemcmd.AppendArg("match");
	systemcmd.AppendArg(matchstring);

#if !defined(WIN32)
	if( can_switch_ids() ) {
		MyString tmp_str;
		tmp_str.formatstr("%d", (int)get_condor_uid());
		SetEnv("VMGAHP_USER_UID", tmp_str.Value());
	}
#endif

	// execute vmgahp with root privilege
	priv_state priv = set_root_priv();
	int ret = my_system(systemcmd);
	// restore privilege
	set_priv(priv);

	if( ret == 0 ) {
		dprintf( D_ALWAYS, "VMUniverseMgr::killVM() is called with "
						"'%s'\n", matchstring );
	}else {
		dprintf( D_ALWAYS, "VMUniverseMgr::killVM() failed!\n");
	}

	return;
}
예제 #19
0
파일: statevar.c 프로젝트: ricksladkey/vile
static int
any_rw_TXT(TBUFF **rp, const char *vp, char **value)
{
    if (rp) {
	tb_scopy(rp, *value);
	return TRUE;
    } else if (vp) {
	SetEnv(value, vp);
	return TRUE;
    } else {
	return FALSE;
    }
}
예제 #20
0
파일: statevar.c 프로젝트: ricksladkey/vile
int
var_CDPATH(TBUFF **rp, const char *vp)
{
    if (rp) {
	tb_scopy(rp, get_cdpath());
	return TRUE;
    } else if (vp) {
	SetEnv(&cdpath, vp);
	return TRUE;
    } else {
	return FALSE;
    }
}
예제 #21
0
EnvironmentVariebles::EnvironmentVariebles(wxXmlNode *node){
	if(node){
		//read values XML 
		wxXmlNode *child = node->GetChildren();
		while(child){
			wxString name = XmlUtils::ReadString(child, wxT("Name"));
			wxString value = XmlUtils::ReadString(child, wxT("Value"));
			SetEnv(name, value);
			child = child->GetNext();
		}
	}else{
		//do nothing
	}
}
예제 #22
0
// Update environment variables
void env_update_settings(BOOL save)
{
    // Clear buffer
    GUI->work_buffer[0]=0;

    // Clock?
    if (GUI->flags&GUIF_CLOCK)
    {
        strcat(GUI->work_buffer,"-clock-");
    }

    // Create icons?
    if (GUI->flags&GUIF_SAVE_ICONS)
    {
        strcat(GUI->work_buffer,"-icons-");
    }

    // File filter?
    if (GUI->flags&GUIF_FILE_FILTER)
    {
        strcat(GUI->work_buffer,"-filter-");
    }

    // Def public screen?
    if (GUI->flags&GUIF_DEFPUBSCR)
    {
        strcat(GUI->work_buffer,"-defpub-");
    }

    // Show icons?
    if (GUI->flags&GUIF_VIEW_ICONS)
    {
        strcat(GUI->work_buffer,"-showicons-");
    }

    // Icon action?
    if (GUI->flags&GUIF_ICON_ACTION)
    {
        strcat(GUI->work_buffer,"-iconaction-");
    }

    // Show all?
    if (GUI->flags&GUIF_SHOW_ALL)
    {
        strcat(GUI->work_buffer,"-showall-");
    }

    // Set variable
    SetEnv("dopus/dopus",GUI->work_buffer,save);
}
예제 #23
0
bool
VMType::createConfigUsingScript(const char* configfile)
{
	vmprintf(D_FULLDEBUG, "Inside VMType::createConfigUsingScript\n");

	if( !configfile || m_scriptname.IsEmpty() ) {
		return false;
	}

	// Set temporary environments for script program
	StringList name_list;

	const char *name;
	ExprTree* expr = NULL;

	m_classAd.ResetExpr();
	while( m_classAd.NextExpr(name, expr) ) {
		if( !strncasecmp( name, "JobVM", strlen("JobVM") ) ||
			!strncasecmp( name, "VMPARAM", strlen("VMPARAM") )) {

			name_list.append(name);
			SetEnv(name, ExprTreeToString(expr));
		}
	}

	ArgList systemcmd;
	if( m_prog_for_script.IsEmpty() == false ) {
		systemcmd.AppendArg(m_prog_for_script);
	}
	systemcmd.AppendArg(m_scriptname);
	systemcmd.AppendArg("createconfig");
	systemcmd.AppendArg(configfile);

	int result = systemCommand(systemcmd, m_file_owner);

	// UnSet temporary environments for script program
	const char *tmp_name = NULL;
	name_list.rewind();
	while( (tmp_name = name_list.next()) != NULL ) {
		UnsetEnv(tmp_name);
	}

	if( result != 0 ) {
		vmprintf(D_ALWAYS, "Failed to create Configuration file('%s') using "
				"script program('%s')\n", configfile, 
				m_scriptname.Value());
		return false;
	}
	return true;
}
예제 #24
0
/*
 * @implemented
 */
int _putenv(const char* val)
{
   int size, result;
   wchar_t *woption;

   size = MultiByteToWideChar(CP_ACP, 0, val, -1, NULL, 0);
   woption = malloc(size* sizeof(wchar_t));
   if (woption == NULL)
      return -1;
   MultiByteToWideChar(CP_ACP, 0, val, -1, woption, size);
   result = SetEnv(woption);
   free(woption);
   return result;
}
예제 #25
0
파일: PopupMenu.cpp 프로젝트: songcser/ALM
HRESULT STDMETHODCALLTYPE CPopupMenu::InvokeCommand( __in CMINVOKECOMMANDINFO *pici)
{
	if(HIWORD(((CMINVOKECOMMANDINFOEX *)pici)->lpVerbW)){
		return S_OK;
	}
	else
	{
		if(1 == LOWORD(pici->lpVerb)){
			SetEnv();
		}
		else if(2 == LOWORD(pici->lpVerb)){
			Update();
		}
		else if(3 == LOWORD(pici->lpVerb)){
			Checkout();
		}
		else if(4 == LOWORD(pici->lpVerb)){
			Commit();
		}
		else if(5 == LOWORD(pici->lpVerb)){
			Checkin();
		}
		else if(6 == LOWORD(pici->lpVerb)){
			Cancel();
		}
		else if(7 == LOWORD(pici->lpVerb)){
			Add();
		}
		else if(8 == LOWORD(pici->lpVerb)){
			Revert();
		}
		else if(9 == LOWORD(pici->lpVerb)){
			Merge();
		}
		else if(10 == LOWORD(pici->lpVerb)){
			ShowLog();
		}
		else if(11 == LOWORD(pici->lpVerb)){
			Diff();
		}
		else if(12 == LOWORD(pici->lpVerb)){
			Compare();
		}
		else if(13 == LOWORD(pici->lpVerb)){
			UpdateRelyFiles();
		}
	}

	return S_OK;
}
예제 #26
0
void DOS_Shell::CMD_SET(char * args) {
	HELP("SET");
	StripSpaces(args);
	std::string line;
	if (!*args) {
		/* No command line show all environment lines */	
		Bitu count=GetEnvCount();
		for (Bitu a=0;a<count;a++) {
			if (GetEnvNum(a,line)) WriteOut("%s\n",line.c_str());			
		}
		return;
	}
	//There are args:
	char * pcheck = args;
	while ( *pcheck && (*pcheck == ' ' || *pcheck == '\t')) pcheck++;
	if (*pcheck && strlen(pcheck) >3 && (strncasecmp(pcheck,"/p ",3) == 0)) E_Exit("Set /P is not supported. Use Choice!");

	char * p=strpbrk(args, "=");
	if (!p) {
		if (!GetEnvStr(args,line)) WriteOut(MSG_Get("SHELL_CMD_SET_NOT_SET"),args);
		WriteOut("%s\n",line.c_str());
	} else {
		*p++=0;
		/* parse p for envirionment variables */
		char parsed[CMD_MAXLINE];
		char* p_parsed = parsed;
		while(*p) {
			if(*p != '%') *p_parsed++ = *p++; //Just add it (most likely path)
			else if( *(p+1) == '%') {
				*p_parsed++ = '%'; p += 2; //%% => % 
			} else {
				char * second = strchr(++p,'%');
				if(!second) continue; *second++ = 0;
				std::string temp;
				if (GetEnvStr(p,temp)) {
					std::string::size_type equals = temp.find('=');
					if (equals == std::string::npos) continue;
					strcpy(p_parsed,temp.substr(equals+1).c_str());
					p_parsed += strlen(p_parsed);
				}
				p = second;
			}
		}
		*p_parsed = 0;
		/* Try setting the variable */
		if (!SetEnv(args,parsed)) {
			WriteOut(MSG_Get("SHELL_CMD_SET_OUT_OF_SPACE"));
		}
	}
}
예제 #27
0
bool
Env::MergeFrom( char const * env_str )
{
	if ( !env_str ) {
		return false;
	}
	const char *ptr = env_str;
	while ( *ptr != '\0' ) {
		// a Windows environment block typically contains stuff like
		// '=::=::\' and '=C:=C:\some\path'; SetEnv will return an error
		// for strings like these, so we'll just silently ignore errors
		// from SetEnv and insert what we can
		//
		SetEnv( ptr );
		ptr += strlen(ptr) + 1;
	}
	return true;
}
예제 #28
0
bool
Env::MergeFrom( char const * const *stringArray )
{
	if( !stringArray ) {
		return false;
	}
	int i;
	bool all_ok = true;
	for( i = 0; stringArray[i] && stringArray[i][0] != '\0'; i++ ) {
		if( !SetEnv( stringArray[i] ) ) {
				// Keep going so that we behave like getenv() in
				// our treatment of invalid entries in the
				// environment.  However, this function still
				// returns error, unlike Import().
			all_ok = false;
		}
	}
	return all_ok;
}
예제 #29
0
int SetEnv( const char *env_var ) 
{
		// this function used if you've already got a name=value type
		// of string, and want to put it into the environment.  env_var
		// must therefore contain an '='.
	if ( !env_var ) {
		dprintf (D_ALWAYS, "SetEnv, env_var = NULL!\n" );
		return FALSE;
	}

		// Assume this type of string passes thru with no problem...
	if ( env_var[0] == 0 ) {
		return TRUE;
	}

	char const *equalpos = NULL;

	if ( ! (equalpos = strchr( env_var, '=' )) ) {
		dprintf (D_ALWAYS, "SetEnv, env_var has no '='\n" );
		dprintf (D_ALWAYS, "env_var = \"%s\"\n", env_var );
		return FALSE; 
	}

		// hack up string and pass to other SetEnv version.
	size_t namelen = equalpos - env_var;
	int valuelen = strlen(env_var) - namelen - 1;

	char *name = new char[namelen+1];
	char *value = new char[valuelen+1];
	strncpy ( name, env_var, namelen );
	strncpy ( value, equalpos+1, valuelen );
	name[namelen] = '\0';
	value[valuelen] = '\0';

	int retval = SetEnv ( name, value );

	delete [] name;
	delete [] value;
	return retval;
}
예제 #30
0
int main() {
    int n, childPid;
    char buf[BUF_MAX_SIZE];
    char execPath[PATH_MAX_LEN];
    char execCmd[CMD_MAX_LEN];
    int cmdLen = 0;
    char* execArgv[BUF_MAX_SIZE];
    int argvNum = 0;
    struct ExecCmd execCmdQueue[CMD_MAX_NUM];
    int cmdNum = 0;

    chdir(WorkDir);

    if(remoteOption) CreateConnection();
    stdoutfd = dup(STDOUT_FILENO);
    stderrfd = dup(STDERR_FILENO);

    /*** a connection come ***/
    for(;;) {

        /*** accept ***/
        if(remoteOption) {
            clilen = sizeof(cli_addr);
            newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
            if(newsockfd < 0) {
                write(STDERR_FILENO, "accept error!\n", 14);
                exit(1);
            }
            //write(STDERR_FILENO, "accept\n", 7);
    
            /*** for remote client, stdout/stderr is client socket ***/
            if(remoteOption){ 
                dup2(newsockfd, STDOUT_FILENO);
                dup2(newsockfd, STDERR_FILENO);
            }
        }
        connectionOption = 1;
        //int line = 1;

        /*** shell start ***/
        while(connectionOption) {
            if(welcomeMsgOption) {
                welcomeMsgOption = WelcomeMsg();
            }
            //printf("%4d", line++);fflush(stdout);
            write(STDOUT_FILENO, "% ", 2);

            /*** clean & initialize variables ***/
            bzero(buf, BUF_MAX_SIZE);
            bzero(execPath, PATH_MAX_LEN);
            bzero(execCmd, CMD_MAX_LEN);
            bzero(execArgv, sizeof(execArgv));
            bzero(execCmdQueue, sizeof(execCmdQueue));
            cmdNum = 0;
            argvNum = 0;
            cmdLen = 0;

            if(remoteOption) ReadCmdLineFromRemote(buf, &n);
            else ReadCmdLine(buf, &n);

            /*** cut input ***/
            char buf2[BUF_MAX_SIZE];
            strncpy(buf2, buf, n);
            strtok(buf2, "\n");
            strtok(buf2, "\r");
            /*write(STDERR_FILENO, "parse cmd line: ", 16);
            write(STDERR_FILENO, buf2, strlen(buf2));
            write(STDERR_FILENO, "\n", 1);*/

            ParsePipe(buf2, execCmdQueue, &cmdNum);

            int i = 0;
            for(; i < cmdNum; ++i) {

                /*** clean & initialize variables ***/
                bzero(execPath, PATH_MAX_LEN);
                bzero(execCmd, CMD_MAX_LEN);
                bzero(execArgv, sizeof(execArgv));
                argvNum = 0;
                cmdLen = 0;

                if(ParseCmdAndArgv(execCmdQueue[i].execCmdLine, execCmd, execArgv, &cmdLen, &argvNum) == -1) {
                    break;
                }

                /*** select a function ***/
                if(!strcmp(execCmd, "setenv")) {
                    SetEnv(argvNum, execArgv);
                }
                else if(!strcmp(execCmd, "printenv")) {
                    PrintEnv();
                }
                else if(!strcmp(execCmd, "\n")) {
                    break;
                }
                else if(!strcmp(execCmd, "exit")) {
                    CloseAllPipe();
                    //ListAllPipe();
                    if(remoteOption) {
                        connectionOption = 0;
                        break;
                    }
                    else {
                        return 0;
                    }
                }
                else {
                    /*** prepare to execute cmd ***/

                    int refreshOption = 0;
                    int stdinOption = 0;
                    int stdoutOption = 0;
                    char* ptrNextCmdLine;
                    if(i+1 < cmdNum) {
                        ptrNextCmdLine = execCmdQueue[i+1].execCmdLine;
                    }

                    /*** | or ! or > pipe ***/
                    if(execCmdQueue[i].pipeType > 0) {
                        CreatePipe(&stdoutOption, &execCmdQueue[i].pipeType, ptrNextCmdLine);
                        
                        SetPipePriority(ptrNextCmdLine, &cmdNum, &refreshOption, &execCmdQueue[i].pipeType);
                        
                        //ListAllPipe();
                    }

                    /*** fork a process to execute the cmd (in child process) ***/
                    if( (childPid = fork()) == -1) {
                        write(STDERR_FILENO, "fork() error.\n", 14);
                    }
                    else if(childPid == 0) {
                        /*** child process ***/

                        if(remoteOption) close(sockfd);

                        SetStdin(&stdinOption);

                        SetStdoutAndStderr(&stdoutOption, &execCmdQueue[i].pipeType);

                        Execute(execCmd, execPath, execArgv, &cmdLen);

                        exit(0);
                    }
                    else {
                        /*** parent process ***/

                        wait();

                        /*** stdout check & close ***/
                        if(stdoutOption == 1) {
                            if(execCmdQueue[i].pipeType == 1 || execCmdQueue[i].pipeType == 2) {
                                //printf("close fd[1]: %d\n", pipesTail->pipefd[1]);fflush(stdout);
                                close(pipesTail->pipefd[1]);
                            }
                            else if(execCmdQueue[i].pipeType == 3 && filepipe != NULL) {
                                //printf("close file, fd: %d\n", pipesTail->pipefd[0]);fflush(stdout);
                                fclose(filepipe);
                                filepipe = NULL;
                                struct PipeStruct* tmpPtr = pipes;
                                struct PipeStruct* tmpPrePtr;
                                pipesTail->priority = 1;
                            }
                        }

                        /*** when stdin complete, close both the r/w pipe fd (that priority==1) ***/
                        struct PipeStruct* ptrPipeStruct = pipes;
                        struct PipeStruct* prePtr = NULL;
                        while(ptrPipeStruct != NULL) {
                            if(ptrPipeStruct->priority == 1) {
                                //printf("close fd[0]: %d\n", ptrPipeStruct->pipefd[0]);fflush(stdout);
                                close(ptrPipeStruct->pipefd[0]);
                                if(ptrPipeStruct == pipes) {
                                    /*** delete the first node ***/
   
                                    if(ptrPipeStruct == pipesTail) {
                                        /*** the first node is also the last node ***/
   
                                        free(ptrPipeStruct);
                                        pipes = NULL;
                                        pipesTail = NULL;
                                        break;
                                    }
                                    else {
                                        pipes = ptrPipeStruct->next;
                                        free(ptrPipeStruct);
                                        ptrPipeStruct = pipes;
                                    }
                                }
                                else if(ptrPipeStruct == pipesTail) {
                                    /*** delete the last node ***/

                                    prePtr->next = NULL;
                                    pipesTail = prePtr;
                                    free(ptrPipeStruct);
                                    break;
                                }
                                else {
                                    prePtr->next = ptrPipeStruct->next;
                                    free(ptrPipeStruct);
                                    ptrPipeStruct = prePtr->next;
                                }

                            }
                            else {
                                prePtr = ptrPipeStruct;
                                ptrPipeStruct = ptrPipeStruct->next;
                            }
                        }

                        /*** refresh the next pipe priority ***/
                        if(refreshOption) {
                            pipesTail->priority = pipesTail->priority - 1;
                        }

                        /*** handle > pipe, end this execCmdQueue ***/
                        if(execCmdQueue[i].pipeType == 3) {
                            break;
                        }
                    }
                }
            }
            RefreshPipe();
        }
        if(remoteOption){
            dup2(stdoutfd, STDOUT_FILENO);
            dup2(stderrfd, STDERR_FILENO);
            close(newsockfd);
        }
        welcomeMsgOption = 1;
        bzero(PATH, sizeof(PATH));
        strcpy(PATH[0], "bin");
        strcpy(PATH[1], ".");
        pathNum = 2;
    }
    if(remoteOption) close(sockfd);
    return 0;
}