int main(int argc, char *argv[]) {
  while (true) {
    char command[kMaxCommandLength + 1];
    readCommand(command, sizeof(command) - 1);
    if (feof(stdin)) break;
    char *arguments[kMaxArgumentCount + 1];
    int count = parseCommandLine(command, arguments, sizeof(arguments)/sizeof(arguments[0]));
    if (count == 0) continue;
    bool builtin = handleBuiltin(arguments);
    if (builtin) continue; // it's been handled, and backgrounding a builtin isn't an option
    bool isBackgroundProcess = strcmp(arguments[count - 1], "&") == 0;
    if (isBackgroundProcess) arguments[--count] = NULL; // overwrite "&"
    pid_t pid = forkProcess();
    if (pid == 0) {
      if (execvp(arguments[0], arguments) < 0) {
	printf("%s: Command not found\n", arguments[0]);
	exit(0);
      }
    }
    
    if (!isBackgroundProcess) {
      waitForChildProcess(pid);
    } else {
      // don't wait for child, and let it roll in the background,
      // but recognize that we currently aren't reaping any background
      // processes when they terminate, and that's something that
      // we need to fix in future iterations of the shell
      printf("%d %s\n", pid, command);
    }
  }
  
  printf("\n");
  return 0;
}
示例#2
0
文件: shell.c 项目: RyanKadri/OpSys
/* This function runs the pipeline of commands. If there are no pipes, the command
 * simply executes. Otherwise, the last command spawns a child process, sets up
 * a pipe with it and waits for it to run (recursively)*/
int runCommands(char** tokens, char** pipes, int numTokens, int numPipes){
	
	/* Simple case*/
	if(numPipes == 0){
		forkProcess(tokens, numTokens);
		exit(0);
	}else{
		
		int i,pid;
		int fd[2];
		
		pipe(fd);

		int commandTokens = 0;
		
		/* Count from the back*/
		for(i = numTokens-1; tokens[i] > pipes[numPipes-1];--i){
			++commandTokens;
		}
		
		pid	= fork();
		
		/* The child is the command before the last one */
		if(pid==0){
			dup2(fd[1],1);
			close(fd[0]);
			/* It sees everything before the last pipe */
			runCommands(tokens, pipes, numTokens-commandTokens, numPipes - 1);
			exit(0);
		}else if(pid == -1){
			perror("fork");
			/* The parent waits on output from the child and then executes*/
		}else{
			dup2(fd[0],0);
			close(fd[1]);
			int got_pid;
			waitAround(pid);
			/* Execute everything after the last pipe*/
			forkProcess(tokens + (char)(numTokens-commandTokens),commandTokens);
			exit(0);
		}
	}
	
}
示例#3
0
文件: main.c 项目: WinLinKer/alilua
int main ( int argc, char *argv[] )
{
    attach_on_exit ( on_master_exit_handler );

    /// 初始化进程命令行信息
    char *cwd = initProcTitle ( argc, argv );

    char *msg = NULL;
    
    if ( getarg ( "cache-size" ) ) {
        msg = getarg ( "cache-size" );
        YAC_CACHE_SIZE = atoi ( msg );
        if(msg[strlen(msg)-1] == 'm')YAC_CACHE_SIZE = YAC_CACHE_SIZE*1024*1024;
        else if(msg[strlen(msg)-1] == 'k')YAC_CACHE_SIZE = YAC_CACHE_SIZE*1024;

    }
    if ( YAC_CACHE_SIZE < 1024*1024*2 ) {
        YAC_CACHE_SIZE = 1024*1024*2;
    }

    if ( !yac_storage_startup ( YAC_CACHE_SIZE/16, YAC_CACHE_SIZE-(YAC_CACHE_SIZE/16), &msg ) ) {
        printf ( "Shared memory allocator startup failed at '%s': %s", msg,
                 strerror ( errno ) );
        exit ( 1 );
    }

    if ( getarg ( "log" ) && strlen ( getarg ( "log" ) ) > 0 ) {
        LOG_FD = fopen ( getarg ( "log" ), "a+" );

        if ( !LOG_FD ) {
            printf ( "fopen %s error\n" , getarg ( "log" ) );
            return -1;
        }

        setvbuf ( LOG_FD , LOG_BUF, _IOFBF , 40960 );
    }

    if ( getarg ( "errorlog" ) && strlen ( getarg ( "errorlog" ) ) > 0 ) {
        ERR_FD = fopen ( getarg ( "errorlog" ), "a+" );

        if ( !ERR_FD ) {
            printf ( "fopen %s error\n" , getarg ( "errorlog" ) );
            return -1;
        }

        setvbuf ( ERR_FD , ERR_BUF, _IOFBF , 4096 );
    }

    hostname[1023] = '\0';
    gethostname ( hostname, 1000 );

    lua_State *L = luaL_newstate();
    luaL_openlibs ( L );
    lua_getglobal ( L, "_VERSION" );
    const char *lua_ver = lua_tostring ( L, -1 );
    lua_getglobal ( L, "jit" );

    if ( lua_istable ( L, -1 ) ) {
        lua_getfield ( L, -1, "version" );

        if ( lua_isstring ( L, -1 ) ) {
            lua_ver = lua_tostring ( L, -1 );
        }
    }

    sprintf ( hostname, "%s/%s", hostname, lua_ver );
    lua_close ( L );

    if ( getarg ( "help" ) ) {
        printf ( "This is the aLiLua/%s Web Server.  Usage:\n"
                 "\n"
                 "    alilua [options]\n"
                 "\n"
                 "Options:\n"
                 "\n"
                 "  --bind=127.0.0.1:80  server bind. or --bind=80 for bind at 0.0.0.0:80\n"
                 "  --daemon             process mode\n"
                 "  --process=number     workers\n"
                 "  --log=file-path      access log\n"
                 "  --errorlog=file-path error log\n"
                 "  --host-route         Special route file path\n"
                 "  --code-cache-ttl     number of code cache time(sec)\n"
                 "  --cache-size         size of YAC shared memory cache (1m or 4096000k)\n"
                 "  \n"
                 "\n",
                 version
               );
        exit ( 0 );
    }

    /// 把进程放入后台
    if ( getarg ( "daemon" ) ) {
        is_daemon = 1;
        daemonize();
    }

    /// 创建4个子进程
    if ( getarg ( "process" ) ) {
        process_count = atoi ( getarg ( "process" ) );

    } else if ( process_count > 32 ) {
        process_count = 32;
    }

    if ( !getarg ( "daemon" ) ) {
        process_count = 1;
    }

    char *bind_addr = "0.0.0.0";

    if ( getarg ( "bind" ) ) {
        bind_addr = getarg ( "bind" );
    }

    char *_port;

    if ( !strstr ( bind_addr, "." ) ) {
        bind_addr = "0.0.0.0";
        _port = getarg ( "bind" );

    } else {
        _port = strstr ( bind_addr, ":" );

        if ( _port ) {
            bind_addr[strlen ( bind_addr ) - strlen ( _port )] = '\0';
            _port = _port + 1;
        }
    }

    int port = default_port;

    if ( _port ) {
        port = atoi ( _port );
    }

    if ( port < 1 ) {
        port = default_port;
    }

    int i = 0, status = 0;
    {
        /// init lua state
        _L = luaL_newstate();
        lua_gc ( _L, LUA_GCSTOP, 0 );
        luaL_openlibs ( _L ); /* Load Lua libraries */
        lua_gc ( _L, LUA_GCRESTART, 0 );

        if ( getarg ( "code-cache-ttl" ) ) { /// default = 60s
            lua_pushnumber ( _L, atoi ( getarg ( "code-cache-ttl" ) ) );
            lua_setglobal ( _L, "CODE_CACHE_TTL" );
        }

        if ( getarg ( "host-route" ) ) {
            lua_pushstring ( _L, getarg ( "host-route" ) );
            lua_setglobal ( _L, "HOST_ROUTE" );
        }

        lua_register ( _L, "errorlog", lua_errorlog );
        lua_register ( _L, "echo", lua_echo );
        lua_register ( _L, "sendfile", lua_sendfile );
        lua_register ( _L, "header", lua_header );
        lua_register ( _L, "clear_header", lua_clear_header );
        lua_register ( _L, "die", lua_die );
        lua_register ( _L, "get_post_body", lua_get_post_body );
        lua_register ( _L, "check_timeout", lua_check_timeout );
        lua_register ( _L, "is_websocket", lua_f_is_websocket );
        lua_register ( _L, "upgrade_to_websocket", lua_f_upgrade_to_websocket );
        lua_register ( _L, "websocket_send", lua_f_websocket_send );
        lua_register ( _L, "sleep", lua_f_sleep );

        lua_register ( _L, "random_string", lua_f_random_string );
        lua_register ( _L, "file_exists", lua_f_file_exists );

        lua_register ( _L, "cache_set", lua_f_cache_set );
        lua_register ( _L, "cache_get", lua_f_cache_get );
        lua_register ( _L, "cache_del", lua_f_cache_del );

        luaopen_fastlz ( _L );
        luaopen_coevent ( _L );
        luaopen_libfs ( _L );
        luaopen_string_utils ( _L );
        luaopen_crypto ( _L );

        lua_pop ( _L, 1 );

        sprintf ( tbuf_4096,
                  "package.path = '%s/lua-libs/?.lua;' .. package.path package.cpath = '%s/lua-libs/?.so;' .. package.cpath",
                  cwd, cwd );
        luaL_dostring ( _L, tbuf_4096 );

        /* Load the file containing the script we are going to run */
        status = luaL_loadfile ( _L, "script.lua" );

        if ( status || lua_resume ( _L, 0 ) ) {
            /* If something went wrong, error message is at the top of */
            /* the stack */
            fprintf ( stderr, "Couldn't load file: %s\n", lua_tostring ( _L, -1 ) );
            exit ( 1 );
        }

        lua_getglobal ( _L, "main" );
        main_handle_ref = luaL_ref ( _L, LUA_REGISTRYINDEX );
    }

    server_fd = network_bind ( bind_addr, port );

    for ( i = 0; i < process_count; i++ ) {
        if ( getarg ( "daemon" ) ) {
            forkProcess ( worker_main );

        } else {
            active_cpu ( 0 );
            new_thread_i ( worker_main, 0 );
        }
    }

    /// 设置进程归属用户
    setProcessUser ( /*user*/ NULL, /*group*/ NULL );

    /// 进入主进程处理
    master_main();

    return 0;
}