Exemplo n.º 1
0
int Awstats::executeUpdate(const char * pName)
{
    const char * pWorking = m_sWorkingDir.c_str();
    char achBuf[8192];
    safe_snprintf( achBuf, 8192, "%s/add-ons/awstats",
            HttpGlobals::s_pServerRoot );
    if ( HttpGlobals::s_psChroot )
        pWorking += HttpGlobals::s_psChroot->len();
    if ( chdir( achBuf ) == -1 )
    {
        LOG_ERR(( "Cannot change to dir [%s]: %s", achBuf, strerror( errno ) ));
        return -1;
    }
    if ( m_iMode == AWS_STATIC )
    {
        safe_snprintf( achBuf, 8192,
            "tools/awstats_buildstaticpages.pl -awstatsprog=wwwroot/cgi-bin/awstats.pl"
            " -dir='%s/html' -update "
            "-configdir='%s/conf' "
            "-config='%s' -lang=en", pWorking, pWorking,
            pName );
    }
    else if ( m_iMode == AWS_DYNAMIC )
    {
        safe_snprintf( achBuf, 8192,
            "wwwroot/cgi-bin/awstats.pl -update -configdir='%s/conf' -config='%s'",
                pWorking, pName );
    }
    else
    {
        LOG_ERR(( "Unknown update method %d", m_iMode ));
        return -1;
    }
    
    setpriority( PRIO_PROCESS, 0, getpriority( PRIO_PROCESS, 0) + 4 );
    int ret = system( achBuf );
    return ret;
}
Exemplo n.º 2
0
int Awstats::executeUpdate(const char *pName)
{
    const char *pWorking = m_sWorkingDir.c_str();
    char achBuf[8192];
    ls_snprintf(achBuf, 8192, "%s/add-ons/awstats",
                MainServerConfig::getInstance().getServerRoot());
    if (ServerProcessConfig::getInstance().getChroot() != NULL)
        pWorking += ServerProcessConfig::getInstance().getChroot()->len();
    if (chdir(achBuf) == -1)
    {
        LS_ERROR("Cannot change to dir [%s]: %s", achBuf, strerror(errno));
        return LS_FAIL;
    }
    if (m_iMode == AWS_STATIC)
    {
        ls_snprintf(achBuf, 8192,
                    "tools/awstats_buildstaticpages.pl -awstatsprog=wwwroot/cgi-bin/awstats.pl"
                    " -dir='%s/html' -update "
                    "-configdir='%s/conf' "
                    "-config='%s' -lang=en", pWorking, pWorking,
                    pName);
    }
    else if (m_iMode == AWS_DYNAMIC)
    {
        ls_snprintf(achBuf, 8192,
                    "wwwroot/cgi-bin/awstats.pl -update -configdir='%s/conf' -config='%s'",
                    pWorking, pName);
    }
    else
    {
        LS_ERROR("Unknown update method %d", m_iMode);
        return LS_FAIL;
    }

    setpriority(PRIO_PROCESS, 0, getpriority(PRIO_PROCESS, 0) + 4);
    int ret = system(achBuf);
    return ret;
}
Exemplo n.º 3
0
static TACommandVerdict getpriority_cmd(TAThread thread,TAInputStream stream)
{
   int which;
   int who  ;
   int res  ;

   // Prepare
   which = readInt( & stream );
   who   = readInt( & stream );
   errno = 0;

   // Execute
   START_TARGET_OPERATION(thread);
   res = getpriority( which, who );
   END_TARGET_OPERATION(thread);

   // Response
   writeInt( thread, res   );
   writeInt( thread, errno );
   sendResponse( thread );

   return taDefaultVerdict;
}
Exemplo n.º 4
0
static void display_thread_sched_attr(char *msg)
{
    int policy, prio;
    struct sched_param param;

    prio = getpriority(PRIO_PROCESS, 0);
    assert(!pthread_getschedparam(pthread_self(), &policy, &param));

    coremu_print("-- tid[%lu] %s start --",
             (unsigned long int)coremu_gettid(), msg);

    coremu_print("policy=%s, priority=%d",
             (policy == SCHED_FIFO) ?
				 "SCHED_FIFO" :
                 (policy == SCHED_RR) ?
				     "SCHED_RR" :
					 (policy == SCHED_OTHER) ?
						 "SCHED_OTHER" :
						 "???", prio);

    coremu_print("-- thr[%lu] %s end --\n",
             (unsigned long int)coremu_gettid(), msg);
}
Exemplo n.º 5
0
// "normal" invoke through a socket connection
static int invoke_remote(int socket_fd, int prog_argc, char **prog_argv, char *prog_name,
                         uint32_t magic_options, bool wait_term, unsigned int respawn_delay,
                         char *splash_file, char *landscape_splash_file)
{
    // Get process priority
    errno = 0;
    int prog_prio = getpriority(PRIO_PROCESS, 0);
    if (errno && prog_prio < 0)
    {
        prog_prio = 0;
    }

    // Connection with launcher process is established,
    // send the data.
    invoker_send_magic(socket_fd, magic_options);
    invoker_send_name(socket_fd, prog_argv[0]);
    invoker_send_exec(socket_fd, prog_name);
    invoker_send_args(socket_fd, prog_argc, prog_argv);
    invoker_send_prio(socket_fd, prog_prio);
    invoker_send_delay(socket_fd, respawn_delay);
    invoker_send_ids(socket_fd, getuid(), getgid());
    if (( magic_options & INVOKER_MSG_MAGIC_OPTION_SPLASH_SCREEN ) != 0)
        invoker_send_splash_file(socket_fd, splash_file);
    if (( magic_options & INVOKER_MSG_MAGIC_OPTION_LANDSCAPE_SPLASH_SCREEN ) != 0)
        invoker_send_landscape_splash_file(socket_fd, landscape_splash_file);
    invoker_send_io(socket_fd);
    invoker_send_env(socket_fd);
    invoker_send_end(socket_fd);

    if (prog_name)
    {
        free(prog_name);
    }

    int exit_status = wait_for_launched_process_to_exit(socket_fd, wait_term);
    return exit_status;
}
Exemplo n.º 6
0
static void print_status(const char *t) {
        int ret;

        if ((ret = sched_getscheduler(0)) < 0) {
                fprintf(stderr, "sched_getscheduler() failed: %s\n", strerror(errno));
                return;
        }

        printf("%s:\n"
               "\tSCHED_RESET_ON_FORK: %s\n",
               t,
               (ret & SCHED_RESET_ON_FORK) ? "yes" : "no");

        if ((ret & ~SCHED_RESET_ON_FORK) == SCHED_RR) {
                struct sched_param param;

                if (sched_getparam(0, &param) < 0) {
                        fprintf(stderr, "sched_getschedparam() failed: %s\n", strerror(errno));
                        return;
                }

                printf("\tSCHED_RR with priority %i\n", param.sched_priority);

        } else if ((ret & ~SCHED_RESET_ON_FORK) == SCHED_OTHER) {
                errno = 0;
                ret = getpriority(PRIO_PROCESS, 0);
                if (errno != 0) {
                        fprintf(stderr, "getpriority() failed: %s\n", strerror(errno));
                        return;
                }

                printf("\tSCHED_OTHER with nice level: %i\n", ret);

        } else
                fprintf(stderr, "Neither SCHED_RR nor SCHED_OTHER.\n");
}
Exemplo n.º 7
0
int os_raiseThreadPriority()
{
	FASTIVA_LATE_IMPL();
    return THREAD_NORM_PRIORITY;
#if 0
    /* Get the priority (the "nice" value) of the current thread.  The
     * getpriority() call can legitimately return -1, so we have to
     * explicitly test errno.
     */
    errno = 0;
    int oldThreadPriority = getpriority(PRIO_PROCESS, 0);
    if (errno != 0) {
        ALOGI("getpriority(self) failed: %s", strerror(errno));
    } else if (oldThreadPriority > ANDROID_PRIORITY_NORMAL) {
        /* Current value is numerically greater than "normal", which
         * in backward UNIX terms means lower priority.
         */
        if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
            set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
        }
        if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
            ALOGI("Unable to elevate priority from %d to %d",
                    oldThreadPriority, ANDROID_PRIORITY_NORMAL);
        } else {
            /*
             * The priority has been elevated.  Return the old value
             * so the caller can restore it later.
             */
            ALOGV("Elevating priority from %d to %d",
                    oldThreadPriority, ANDROID_PRIORITY_NORMAL);
            return oldThreadPriority;
        }
    }
    return INT_MAX;
#endif
}
Exemplo n.º 8
0
void os_changeThreadPriority(Thread* thread, int newPriority)
{
    if (newPriority < 1 || newPriority > 10) {
        ALOGW("bad priority %d", newPriority);
        newPriority = 5;
    }

    int newNice = kNiceValues[newPriority-1];
    pid_t pid = thread->systemTid;

    if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
        set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
    } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
        set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
    }

    if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
        std::string threadName(dvmGetThreadName(thread));
        ALOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s",
        pid, threadName.c_str(), newPriority, newNice, strerror(errno));
    } else {
        ALOGV("setPriority(%d) to prio=%d(n=%d)", pid, newPriority, newNice);
    }
}
Exemplo n.º 9
0
void opticsmountGSP::init()
{
/////////////////// Set process priorities

	int prior;
	int dummy1;
	///  set process priority of ueye usb daemon to highest possible value
	char reniceCmd[100];
	string processIDofUeyeDeamonStr;
	int processIDofUeyeDeamon;
	char pidOfCmd[100];
	sprintf(pidOfCmd, "pidof ueyeusbd");

	processIDofUeyeDeamonStr = this->execAndReturnSystemOutput(pidOfCmd);
	processIDofUeyeDeamon = atoi(processIDofUeyeDeamonStr.c_str());
	sprintf(reniceCmd, "sudo renice -20 %d", processIDofUeyeDeamon);
	dummy1 = system(reniceCmd);
	prior = getpriority(PRIO_PROCESS, processIDofUeyeDeamon);
	printf("\n ueyeusbd process priority set to: %d\n",prior);

	///  set process priority of TestProject process to a value slightly lower than ueye usb daemon
	setpriority(PRIO_PROCESS,0,-15);
	usleep(10000);
	prior = getpriority(PRIO_PROCESS,0);
	printf(" TestProject process priority set to: %d\n",prior);

	this->useBackgroundTask = false;

	prevImageTimeStamp = 0;

/////////////////// Path Initializations

	sprintf(this->calibParamDir, "/opt/GogglesOptics/Calib_Params/%s", this->calibParamSetName);

/////////////////// Camera Initialization section

	if (cameras.useCameras)
	{
		// Initialize 2 cameras
		GSPretVal = cameras.initTwoCameras(); // Errors handled within functions
		if (GSPretVal != 0)
		{
			printf("Cameras could not be initialized!\n");
			return exit(1);
		}
		// Start 2 cameras
		GSPretVal = cameras.startTwoCameras(); // Errors handled within functions
		if (GSPretVal != 0)
		{
			printf("Cameras could not be started!\n");
			return exit(1);
		}
	}

///////////////////

/////////////////// Image Rectification Initialization

	GSPretVal = rectifier.calcRectificationMaps(cameras.getImageWidth(), cameras.getImageHeight(), this->calibParamDir);
	if (GSPretVal != 0)
	{
		cout << "Rectification maps could not be processed!" << endl;
	}

/////////////////// Data Storage Initialization

	datastorage.initDataStorage(this->opticsmountName, this->camera_ID, this->runPath, this->cameras.getImageWidth(), this->cameras.getImageHeight());
	if (datastorage.autoImageStorage) {

		// create image-datastorage thread
		GSPretVal = pthread_create(&ImageStorageThread, NULL, this->imageStorage_thread_Helper, this);
		if (GSPretVal != 0)
		{
			printf("pthread_create ImageStorageThread failed\n");
			return exit(1);
		}

	}
///////////////////

///////////////////  Initialization of OpenCV Mats with correct Size (depending on cameras.reduceImageSizeTo320x240)

	leftImage.create(cameras.getImageHeight(), cameras.getImageWidth(), CV_8UC1);
	rightImage.create(cameras.getImageHeight(), cameras.getImageWidth(), CV_8UC1);

///////////////////

}
Exemplo n.º 10
0
int main(int argc, char *argv[]) {
	int efd, retval, prio;
	uint64_t u;
	ssize_t s;
	uid_t uid;
	fd_set set;
	char *memcg_path;
	struct timeval timeout;
	#ifndef NO_GPL
	char *pathcopy, *progname, cmdline[1024], *tty;
	int istty = 1;
	pid_t pgid;
	#endif

	/* maybe save a tiny number of bytes, because we can */
	mallopt(M_MXFAST, 0);

	if(argc > 2) {
		usage(argv[0]);
		exit(1);
	} else if(argc > 1 && argv[1][0] == '-') {
		/* any attempt at -helpme, etc */
		usage(argv[0]);
		return 1;
	}
	

	uid = getuid();
	/* don't monitor root */
	if(uid == 0)
		return 0;

	/* used for cmdline when this is not a tty */
	pgid = getpgrp();

	daemonize();

	/* be nice */
	prio = getpriority(PRIO_PROCESS, getpid());
	if(prio < TARGET_NICE)
		setpriority(PRIO_PROCESS, getpid(), TARGET_NICE);

	if(argc == 2)
		memcg_path = strdup(argv[1]);
	else
		memcg_path = get_cgroup_path();

	/* set cmdline for ps, top, etc. if you're not concerned about GPL */
	#ifndef NO_GPL
	pathcopy = strdup(argv[0]);
	progname = basename(pathcopy);
	initproctitle(argc, argv);
	tty = getenv("SSH_TTY");
	if(tty == NULL) {
		istty = 0;
		tty = malloc(256);
		snprintf(tty, 256, "[notty: pgid=%d]", pgid);
	}
	snprintf(cmdline, 1024, "%s %s", tty, memcg_path);
	setproctitle(progname, cmdline);
	if(!istty)
		free(tty);
	free(pathcopy);
	#endif


	efd = open_event_fd(memcg_path);

	free(memcg_path);

	while(1) {
		/* Check periodically if the user has other processes.
		   Exit if none exist */
		timeout.tv_sec = TIMEOUT_SECONDS;
		timeout.tv_usec = 0;
		FD_ZERO(&set);
		FD_SET(efd, &set);

		/* check for data in efd (i.e. oom triggered) */
		retval = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
		if(retval == -1) {
			handle_error("select returned -1");
		} else if(retval == 0) {
			if(!pipe_alive())
				return 0;
		} else {
			/* select() found data */
			s = read(efd, &u, sizeof(uint64_t));
			if (s != sizeof(uint64_t)) 
				handle_error("reading from event fd");

			/* Wait a moment for the oom-killer to take effect. */
			sleep(4);
			writeToTTY();
		}
	}
	return 2;
}
Exemplo n.º 11
0
int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
{
	unsigned opt;
	char *signame;
	char *startas;
	char *chuid;
#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
//	char *retry_arg = NULL;
//	int retries = -1;
	char *opt_N;
#endif

	INIT_G();

	opt = GETOPT32(argv, "^"
		"KSbqtma:n:s:u:c:x:p:"
		IF_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:")
			/* -K or -S is required; they are mutually exclusive */
			/* -p is required if -m is given */
			/* -xpun (at least one) is required if -K is given */
			/* -xa (at least one) is required if -S is given */
			/* -q turns off -v */
			"\0"
			"K:S:K--S:S--K:m?p:K?xpun:S?xa"
			IF_FEATURE_START_STOP_DAEMON_FANCY("q-v"),
		LONGOPTS
		&startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
		IF_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
		/* We accept and ignore -R <param> / --retry <param> */
		IF_FEATURE_START_STOP_DAEMON_FANCY(,NULL)
	);

	if (opt & OPT_s) {
		signal_nr = get_signum(signame);
		if (signal_nr < 0) bb_show_usage();
	}

	if (!(opt & OPT_a))
		startas = execname;
	if (!execname) /* in case -a is given and -x is not */
		execname = startas;
	if (execname) {
		G.execname_sizeof = strlen(execname) + 1;
		G.execname_cmpbuf = xmalloc(G.execname_sizeof + 1);
	}

//	IF_FEATURE_START_STOP_DAEMON_FANCY(
//		if (retry_arg)
//			retries = xatoi_positive(retry_arg);
//	)
	//argc -= optind;
	argv += optind;

	if (userspec) {
		user_id = bb_strtou(userspec, NULL, 10);
		if (errno)
			user_id = xuname2uid(userspec);
	}
	/* Both start and stop need to know current processes */
	do_procinit();

	if (opt & CTX_STOP) {
		int i = do_stop();
		return (opt & OPT_OKNODO) ? 0 : (i <= 0);
	}

	if (G.found_procs) {
		if (!QUIET)
			printf("%s is already running\n%u\n", execname, (unsigned)G.found_procs->pid);
		return !(opt & OPT_OKNODO);
	}

#ifdef OLDER_VERSION_OF_X
	if (execname)
		xstat(execname, &G.execstat);
#endif

	*--argv = startas;
	if (opt & OPT_BACKGROUND) {
#if BB_MMU
		bb_daemonize(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS + DAEMON_DOUBLE_FORK);
		/* DAEMON_DEVNULL_STDIO is superfluous -
		 * it's always done by bb_daemonize() */
#else
		/* Daemons usually call bb_daemonize_or_rexec(), but SSD can do
		 * without: SSD is not itself a daemon, it _execs_ a daemon.
		 * The usual NOMMU problem of "child can't run indefinitely,
		 * it must exec" does not bite us: we exec anyway.
		 */
		pid_t pid = xvfork();
		if (pid != 0) {
			/* parent */
			/* why _exit? the child may have changed the stack,
			 * so "return 0" may do bad things */
			_exit(EXIT_SUCCESS);
		}
		/* Child */
		setsid(); /* detach from controlling tty */
		/* Redirect stdio to /dev/null, close extra FDs */
		bb_daemon_helper(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS);
#endif
	}
	if (opt & OPT_MAKEPID) {
		/* User wants _us_ to make the pidfile */
		write_pidfile(pidfile);
	}
	if (opt & OPT_c) {
		struct bb_uidgid_t ugid;
		parse_chown_usergroup_or_die(&ugid, chuid);
		if (ugid.uid != (uid_t) -1L) {
			struct passwd *pw = xgetpwuid(ugid.uid);
			if (ugid.gid != (gid_t) -1L)
				pw->pw_gid = ugid.gid;
			/* initgroups, setgid, setuid: */
			change_identity(pw);
		} else if (ugid.gid != (gid_t) -1L) {
			xsetgid(ugid.gid);
			setgroups(1, &ugid.gid);
		}
	}
#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
	if (opt & OPT_NICELEVEL) {
		/* Set process priority */
		int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
		if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
			bb_perror_msg_and_die("setpriority(%d)", prio);
		}
	}
#endif
	execvp(startas, argv);
	bb_perror_msg_and_die("can't execute '%s'", startas);
}
Exemplo n.º 12
0
//static uint8_t Vbuffer[7.0*5.6*3];
//AVDMGenericVideoStream *getFirstVideoFilter( void)
//
//_____________________________________________________________
void GUI_PlayAvi(bool forceStop)
{
    uint32_t  time_e, time_a = 0;
    uint32_t err = 0, acc = 0;
    uint32_t max;

    uint32_t framelen,flags;
    AVDMGenericVideoStream *filter;

    vids = 0, auds = 0, dauds = 0;
    // check we got everything...
    if (!avifileinfo)
	return;
  if((curframe+1)>= avifileinfo->nb_frames-1)
  {
      printf("No frame left\n");
      return;
   }
    if (avifileinfo->fps1000 == 0)
        return;
    if (playing || forceStop)
      {
        stop_req = 1;
        return;
      }

	uint32_t priorityLevel;

	originalPriority = getpriority(PRIO_PROCESS, 0);
	prefs->get(PRIORITY_PLAYBACK,&priorityLevel);
	setpriority(PRIO_PROCESS, 0, ADM_getNiceValue(priorityLevel));

  uint32_t played_frame=0;
  uint32_t remaining=avifileinfo->nb_frames-curframe;

    
    if(getPreviewMode()==ADM_PREVIEW_OUTPUT)
    {
            filter=getLastVideoFilter(curframe,remaining);
    }
    else
    {
            filter=getFirstVideoFilter(curframe,remaining );
    }
    
    max=filter->getInfo()->nb_frames;

    // compute how much a frame lasts in ms
    one_frame = (uint32_t) floor(1000.*1000.*10. / filter->getInfo()->fps1000);
    err = one_frame % 10;
    one_frame /= 10; // Duration of a frame in ms, err =leftover in 1/10 ms
    
    // go to RealTime...    
    printf("One frame : %lu, err=%lu ms\n", one_frame, err);
    
    // prepare 1st frame

    stop_req = 0;
    playing = 1;

#ifdef HAVE_AUDIO
    ComputePreload();
#endif
    
     
     //renderStartPlaying();
// reset timer reference
    resetTime();
    admPreview::deferDisplay(1,curframe);
    admPreview::update(played_frame);
    do
    {
        vids++;
        admPreview::displayNow(played_frame);;
        update_status_bar();
        if (time_a == 0)
            time_a = getTime(0);
        // mark !
        //printf("\n Rendering %lu frame\n",curframe);
        // read frame in chunk

        if((played_frame)>=(max-1))
        {
            printf("\nEnd met (%lu  / %lu )\n",played_frame,max);
            goto abort_play;
         }
        
        admPreview::update(played_frame+1);;
	curframe++;
	played_frame++;

#ifdef HAVE_AUDIO
	  FillAudio();
#endif

	  time_e = getTime(1);
	  acc += err;
	  if (acc > 10)
	    {
		acc -= 10;
		time_a++;
	    }
	  time_a += one_frame;
	  // delta a is next frame time
	  // time is is current time
	  delta = time_a - time_e;
	  if (delta <= 0)
	    {
		//if(delta<-19)  // allow 19 ms late without warning...
		// tick seems to be ~ 18 ms
		//printf("\n Late ....,due : %lu ms / found : %lu \n",
		//                                              time_a,time_e); 
		// a call to whatever sleep function will last at leat 10 ms
		// give some time to GTK                
	
	  } else
	    {
		// a call to whatever sleep function will last at leat 10 ms
		// give some time to GTK                		
		if (delta > 10)
		    GUI_Sleep(delta - 10);
	    }
     	//
            UI_purge();
            if(getPreviewMode()==ADM_PREVIEW_SEPARATE )
            {
              UI_purge();
              UI_purge(); 
            }
      }
    while (!stop_req);

abort_play:
		// ___________________________________
    // Flush buffer   
    // go back to normal display mode
    //____________________________________
    playing = 0;
          
	   getFirstVideoFilter( );

           admPreview::deferDisplay(0,0);
           UI_purge();
           // Updated by expose ? 
           admPreview::update(curframe);
           UI_purge();
     	   update_status_bar();
#ifdef HAVE_AUDIO
    if (currentaudiostream)
      {
	  if (wavbuf)
	      ADM_dealloc(wavbuf);
          deleteAudioFilter(NULL);
	  currentaudiostream->endDecompress();
	  AVDM_AudioClose();

      }
#endif
    // done.

	setpriority(PRIO_PROCESS, 0, originalPriority);
};
Exemplo n.º 13
0
NvResult CNvThreadingLinux::ThreadCreate(Handle *puThreadHandle, U32(*pFunc)(void *pParam), void *pParam, S32 sPriority)
{
    // Assume invalid handle
    *puThreadHandle = NV_HANDLE_INVALID;

    // Allocate thread handle
    CNvThreadData *pThreadData = new CNvThreadData;

    if (!pThreadData)
    {
        return RESULT_OUT_OF_HANDLES;
    }

#if (NV_PROFILE==1)
    getitimer(ITIMER_PROF, &pThreadData->profTimer);
#endif

    // Store thread parameters
    pThreadData->pFunc = pFunc;
    pThreadData->pParam = pParam;
    pThreadData->pid = 0;

    // Query policy and priority from calling thread
    struct sched_param oSched;

    if (pthread_getschedparam(pthread_self(), &m_iSchedPolicy, &oSched) == 0)
    {
        // Set base priority from calling thread
        if (m_iSchedPolicy == SCHED_OTHER)
            m_iSchedPriorityBase = getpriority(PRIO_PROCESS, 0);
        else
            m_iSchedPriorityBase = oSched.sched_priority;

        // Set minimum and maximum priority limits
        m_iSchedPriorityMin = sched_get_priority_min(m_iSchedPolicy);
        m_iSchedPriorityMax = sched_get_priority_max(m_iSchedPolicy);

        if (m_iSchedPolicy == SCHED_OTHER)
        {
            m_iSchedPriorityMin = -20; // setpriority minimum
            m_iSchedPriorityMax =  19; // setpriority maximum
        }
    }

    // Initialize thread attributes
    pthread_attr_init(&pThreadData->thread_attr);

    // Always inherit scheduling!
    pthread_attr_setinheritsched(&pThreadData->thread_attr, PTHREAD_INHERIT_SCHED);

    // Create thread mutex and condition
    pthread_mutex_init(&pThreadData->mutex, NULL);
    pthread_cond_init(&pThreadData->condition, NULL);

    // Create actual thread and add to thread map
    if (pthread_create(&pThreadData->thread, &pThreadData->thread_attr, ThreadFunc, (void *)pThreadData))
    {
        delete pThreadData;
        return RESULT_OUT_OF_HANDLES;
    }

    // Wait for thread initialization
    pthread_mutex_lock(&pThreadData->mutex);

    while (pThreadData->pid == 0)
        pthread_cond_wait(&pThreadData->condition, &pThreadData->mutex);

    pthread_mutex_unlock(&pThreadData->mutex);

    // Set thread priority
    ThreadPrioritySet(pThreadData, sPriority);

    // Return pThreadData as casting to Handle
    *puThreadHandle = reinterpret_cast<Handle>(pThreadData);

    return RESULT_OK;
}
Exemplo n.º 14
0
/// Launch the auth server
extern int main(int argc, char** argv)
{
    // Command line parsing to get the configuration file name
    char const* configFile = _TRINITY_REALM_CONFIG;
    int count = 1;
    while (count < argc)
    {
        if (strcmp(argv[count], "-c") == 0)
        {
            if (++count >= argc)
            {
                printf("Runtime-Error: -c option requires an input argument\n");
                usage(argv[0]);
                return 1;
            }
            else
                configFile = argv[count];
        }
        ++count;
    }

    if (!sConfigMgr->LoadInitial(configFile))
    {
        printf("Invalid or missing configuration file : %s\n", configFile);
        printf("Verify that the file exists and has \'[authserver]\' written in the top of the file!\n");
        return 1;
    }

    sLog->outString("%s (authserver)", _FULLVERSION);
    sLog->outString("<Ctrl-C> to stop.\n");

    sLog->outString("                       ░                                ░");
    sLog->outString("              ▄▓▄    ░          ░░░▄▄▄▄▄▄▄▄▄▄░░░░         ░");
    sLog->outString("               ▀     ░ ░   ▄▄▄██▓▓▓▓▓▓▓███▓▓▓▓▓▓▓▓▄▄▄   ░ ░");
    sLog->outString("                    ▄▄▄██████▓▓▓▓▓▓▓▓▓▓▓█▓▓▓▓▓▓▓▓▓▓██████▄▄▄");
    sLog->outString("                 ▄███▀▀  ▄██▓▓▓▓█████▓▓▓▓▓▓█████▓▓▓▓▓█▄  ▀▀███▄░");
    sLog->outString("                ▓█▓   ░   ▀████████████▓▓████████████▀    ░ ░▓█▓░");
    sLog->outString("               ▓██▌ ░░  ▒    ▀▀▀██████▓▓▓███████▀▀▀    ▒   ░ ▐██▓░");
    sLog->outString("               ▐██▄░░░   ▓▓       ▀▀███▓████▀▀       ▓▓    ░░▄██▌");
    sLog->outString("               ░▀██▌ ░░    ▀██▄    ░░ ▄▒█▄       ▄██▀    ░░░▐██▀░");
    sLog->outString("             ▄▒▒▒▄▀█▄▄ ░░░░    ░░▄▄▄▓▓▓█▓▓▓▄▄▄▄░░     ░░░ ▄▄▓▀▄▒▒▄▄");
    sLog->outString("            ▐▓▓▓▓▓███████▄▄▄▄█▒▓▓▓▓▓███████▓▓▓▓▒▒▒▒▄▄▄▄███████▓▓▓▓▓▌");
    sLog->outString("           ░▓█▓▓█████████████████████▀▀ ▀▀▀█████▓▓▓▓▓████████████▓▓▓ ░");
    sLog->outString("            ▐█▓▓▓█████▓▓▓█████▓███▀░  ▄▓▄   ░▀████▓██████████████▓▓▌");
    sLog->outString("             ▀▀█▒▒▓▓▓▓▀▀░ ▀▀▀██▓█▌░ ░▓█▓██▄ ░▐██▓▓█▀▀▀  ▀▀██▓▓▓▒▒▀▀");
    sLog->outString("                  ▀ ░░ ▄    ▒█▓▓▓█▄ ▐██▓██▌░▄███▓▓█▒    ▄ ▄  ▀  ░");
    sLog->outString(" ▄        ▄   ▄ ▄▄▄▄▄▄▀█▄ ░▓█▓▓▓████▄█▓▓▓█▄██████▓▓█▓░ ▄█▀█▄▄▄▄▄ ▄   ▄        ▄");
    sLog->outString("        ▄   ▄ ▄ ▄▄▄▄▄▄▀▄▄ ▀█▓▓▓████████▓██████████▓▓█▀ ▄▄▀▄▄▄▄▄▄ ▄ ▄   ▄");
    sLog->outString("                     █▀█  ▒▄ ▄▀▀▀▀▀████▓▓████▀▀▀▀▀▄ ▄▒  █▀█");
    sLog->outString("                     ▓ ▓ ░▓█▓▐██▀▄▄▄ ▄▄ ▄▄▄ ▄▄▄▀▓█▌▓█▓░ ▓ ▓");
    sLog->outString("                     ▒ ▒ ▐█▒ ▐▓░ ▐▓░ ▐▓░▐█▌ ░▓▌  ▒▌ ▒█▌ ▒ ▒");
    sLog->outString("                     ░ ░ ▀   ▀ ▄ ▀  ▄ ▀▄ ▀ ▄  ▀ ▄ ▀   ▀ ░ ░");
    sLog->outString("                     ░ ░        ▀ ░▀ ▀▀ ▀▀▀ ▀░ ▀        ░ ░");
    sLog->outString("                     ░ ░         ▀▓▓▓▓██████▓▓▀         ░ ░");
    sLog->outString("              ReinsCoreWotlk 2016(c) Open-sourced Game Emulation ");
    sLog->outString("         <https://github.com/ReinsCoreWotlk/Core> ReinsCoreWotlk 3.3.5 ");

    sLog->outString("Using configuration file %s.", configFile);

    sLog->outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));

#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
    ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#else
    ACE_Reactor::instance(new ACE_Reactor(new ACE_TP_Reactor(), true), true);
#endif

    sLog->outBasic("Max allowed open files is %d", ACE::max_handles());

    // authserver PID file creation
    std::string pidFile = sConfigMgr->GetStringDefault("PidFile", "");
    if (!pidFile.empty())
    {
        if (uint32 pid = CreatePIDFile(pidFile))
            sLog->outError("Daemon PID: %u\n", pid);
        else
        {
            sLog->outError("Cannot create PID file %s.\n", pidFile.c_str());
            return 1;
        }
    }

    // Initialize the database connection
    if (!StartDB())
        return 1;

    // Initialize the log database
    sLog->SetLogDB(false);
    sLog->SetRealmID(0);                                               // ensure we've set realm to 0 (authserver realmid)

    // Get the list of realms for the server
    sRealmList->Initialize(sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 20));
    if (sRealmList->size() == 0)
    {
        sLog->outError("No valid realms specified.");
        return 1;
    }

    // Launch the listening network socket
    RealmAcceptor acceptor;

    int32 rmport = sConfigMgr->GetIntDefault("RealmServerPort", 3724);
    if (rmport < 0 || rmport > 0xFFFF)
    {
        sLog->outError("Specified port out of allowed range (1-65535)");
        return 1;
    }

    std::string bind_ip = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0");

    ACE_INET_Addr bind_addr(uint16(rmport), bind_ip.c_str());

    if (acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
    {
        sLog->outError("Auth server can not bind to %s:%d", bind_ip.c_str(), rmport);
        return 1;
    }

    // Initialize the signal handlers
    AuthServerSignalHandler SignalINT, SignalTERM;

    // Register authservers's signal handlers
    ACE_Sig_Handler Handler;
    Handler.register_handler(SIGINT, &SignalINT);
    Handler.register_handler(SIGTERM, &SignalTERM);

#if defined(_WIN32) || defined(__linux__)
    
    ///- Handle affinity for multiple processors and process priority
    uint32 affinity = sConfigMgr->GetIntDefault("UseProcessors", 0);
    bool highPriority = sConfigMgr->GetBoolDefault("ProcessPriority", false);

#ifdef _WIN32 // Windows
    
    HANDLE hProcess = GetCurrentProcess();
    if (affinity > 0)
    {
        ULONG_PTR appAff;
        ULONG_PTR sysAff;
        
        if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
        {
            // remove non accessible processors
            ULONG_PTR currentAffinity = affinity & appAff;
            
            if (!currentAffinity)
                sLog->outError("server.authserver", "Processors marked in UseProcessors bitmask (hex) %x are not accessible for the authserver. Accessible processors bitmask (hex): %x", affinity, appAff);
            else if (SetProcessAffinityMask(hProcess, currentAffinity))
                sLog->outString("server.authserver", "Using processors (bitmask, hex): %x", currentAffinity);
            else
                sLog->outError("server.authserver", "Can't set used processors (hex): %x", currentAffinity);
        }
    }
    
    if (highPriority)
    {
        if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
            sLog->outString("server.authserver", "authserver process priority class set to HIGH");
        else
            sLog->outError("server.authserver", "Can't set authserver process priority class.");
    }
    
#else // Linux
    
    if (affinity > 0)
    {
        cpu_set_t mask;
        CPU_ZERO(&mask);

        for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i)
            if (affinity & (1 << i))
                CPU_SET(i, &mask);

        if (sched_setaffinity(0, sizeof(mask), &mask))
            sLog->outError("server.authserver", "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno));
        else
        {
            CPU_ZERO(&mask);
            sched_getaffinity(0, sizeof(mask), &mask);
            sLog->outString("server.authserver", "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask));
        }
    }

    if (highPriority)
    {
        if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY))
            sLog->outError("server.authserver", "Can't set authserver process priority class, error: %s", strerror(errno));
        else
            sLog->outString("server.authserver", "authserver process priority class set to %i", getpriority(PRIO_PROCESS, 0));
    }
    
#endif
#endif

    // maximum counter for next ping
    uint32 numLoops = (sConfigMgr->GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
    uint32 loopCounter = 0;

    // possibly enable db logging; avoid massive startup spam by doing it here.
    if (sConfigMgr->GetBoolDefault("EnableLogDB", false))
    {
        sLog->outString("Enabling database logging...");
        sLog->SetLogDB(true);
    }

    // Wait for termination signal
    while (!stopEvent)
    {
        // dont move this outside the loop, the reactor will modify it
        ACE_Time_Value interval(0, 100000);

        if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
            break;

        if ((++loopCounter) == numLoops)
        {
            loopCounter = 0;
            sLog->outDetail("Ping MySQL to keep connection alive");
            LoginDatabase.KeepAlive();
        }
    }

    // Close the Database Pool and library
    StopDB();

    sLog->outString("Halting process...");
    return 0;
}
void ps_instance_dump(int pid)
{
	char statline[BUFFERSIZE*2];
    struct stat stats;
    process_info psinfo;
    FILE *ps;
    struct passwd *pw;
    int n;

    memset(&psinfo, 0, sizeof(process_info));

    psinfo.pid = pid;

    snprintf(statline, BUFFERSIZE*2, "/proc/%d", pid);
    stat(statline, &stats);

	psinfo.uid = (int) stats.st_uid;

    pw = getpwuid(stats.st_uid);
    if(pw == 0)
    {
    	snprintf(psinfo.owner, 80, "%d", (int)stats.st_uid);
    }
    else
    {
    	strncpy(psinfo.owner, pw->pw_name, 80);
    }


    snprintf(statline, BUFFERSIZE*2, "/proc/%d/stat", pid);
    ps = fopen(statline, "r");
    if (ps != 0)
    {

        /* Scan rest of string. */
        fscanf(ps, "%*d %*s %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
                     "%lu %lu %*d %*d %*d %*d %d %*lu %lu %*lu %ld",
                     &psinfo.status, &psinfo.delta_utime, &psinfo.delta_stime,
					 &psinfo.threadnum, &psinfo.start_time, &psinfo.rss);

        fclose(ps);
    }

    snprintf(statline, BUFFERSIZE*2, "/proc/%d/cmdline", pid);
    ps = fopen(statline, "r");
    if(ps == 0) {
    	n = 0;
    }
    else
    {
    	n = fread(psinfo.name, 1, 80, ps);
    	fclose(ps);
    	if(n < 0) n = 0;
    }
    psinfo.name[n] = 0;

    if(strlen(psinfo.name) == 0)
    {
        snprintf(statline, BUFFERSIZE*2, "/proc/%d/stat", pid);
        ps = fopen(statline, "r");
        if(ps!= 0)
        {
        	n = fscanf(ps, "%d (%s)", &pid, psinfo.name);
        	fclose(ps);
        	if(n == 2)
        		psinfo.name[strlen(psinfo.name)-1] = 0;
        }
    }

    psinfo.nice = getpriority(PRIO_PROCESS, psinfo.pid);

    if(filter_by_system == 1)
    {
    	if((strcmp(psinfo.owner, "root") != 0) &&
    	   (strstr(psinfo.name, "/system/") == 0) &&
    	   (strstr(psinfo.name, "/sbin/") == 0))
    		ps_list_add(&psinfo);
    	else
    		ps_system_add(&psinfo);

    }
    else
    {
    	ps_list_add(&psinfo);
    }

}
Exemplo n.º 16
0
// deliver data that is already available
void datacloud::deliverdata(databuf *hfield,databuf *texture,databuf *fogmap,BOOLINT immediate,int *col,int *row,int *hlod,int *tlod)
   {
   float prio,p;

   jobqueueelem *job,*scan;

   BOOLINT isavailable;

   // start periodical tasks
   if (!immediate)
      {
      if (!DELIVERED)
         {
         // delete delayed jobs
         deletedelayedjobs();

         // delete delayed tiles
         deletedelayedtiles();

         // delete expired tiles
         deleteexpiredtiles();

         // shrink cache to maximum allowed size
         shrinkcache(MAXSIZE*1024*1024);
         }

      // load pending tiles in the background
      startthread();
      }

   // check deferred data delivery
   if (!immediate)
      if (DELIVERED)
         // stop deferred data delivery if time is up
         if (gettime()-DELIVERYSTART>TIMESLOT)
            {
            DELIVERED=FALSE;
            return;
            }

   // scan jobs
   if (!immediate)
      {
      prio=0.0f;

      job=NULL;
      scan=JOBQUEUETAIL;

      while (scan!=NULL)
         {
         p=0.0f;

         isavailable=TRUE;

         // check the availability of all required maps:

         if (scan->hfield!=NULL)
            if (!scan->hfield->isavailable) isavailable=FALSE;
            else p=getpriority(scan->hfield);

         if (scan->texture!=NULL)
            if (!scan->texture->isavailable) isavailable=FALSE;

         if (scan->fogmap!=NULL)
            if (!scan->fogmap->isavailable) isavailable=FALSE;

         // check the priority of the job
         if (isavailable && p>=prio)
            {
            prio=p;
            job=scan;
            }

         scan=scan->prev;
         }
      }
   else job=JOBQUEUE;

   // deferred data delivery
   if (job!=NULL)
      {
      // return maps
      if (job->hfield!=NULL) *hfield=*(job->hfield->tile);
      if (job->texture!=NULL) *texture=*(job->texture->tile);
      if (job->fogmap!=NULL) *fogmap=*(job->fogmap->tile);

      // return tile position
      if (col!=NULL) *col=job->col;
      if (row!=NULL) *row=job->row;

      // return level of detail
      if (hlod!=NULL) *hlod=job->hlod;
      if (tlod!=NULL) *tlod=job->tlod;

      // check for immediate delivery
      if (immediate) DELIVERED=FALSE;
      // remember starting time of deferred delivery
      else if (!DELIVERED)
         {
         DELIVERED=TRUE;
         DELIVERYSTART=gettime();
         }

      // remove finished job from queue
      deletejob(job);
      }
   else DELIVERED=FALSE;
   }
Exemplo n.º 17
0
uint8_t AVDMGenericAudioStream::buildAudioTimeLine(void)
{

uint32_t in,d=0,rd=0,ms10,offset=0,index=0; //,left=0,len=0;;
uint32_t retry=50;
		// we do nothing in case of WAV or unhandler stream
  		// that left only MP3 for now ...
     if (_wavheader->encoding != WAV_MP3 &&_wavheader->encoding != WAV_MP2 )
      {	
	  return 0;
      }
      // in case of mpeg3 we will build a pseudo memory map
      // one tick is 10 ms
      // 100*3600*2*4= 360*8*1000=3000 000= 3 meg
      // for a 2 hour movie
      // should be acceptable

	  uint32_t originalPriority = getpriority(PRIO_PROCESS, 0);
	  uint32_t priorityLevel;

	  prefs->get(PRIORITY_INDEXING,&priorityLevel);
	  setpriority(PRIO_PROCESS, 0, ADM_getNiceValue(priorityLevel));

      goTo(0);  //rewind
      printf("\n scanning timeline\n");
      // ms10 is the raw length of 10 ms of uncompressed audio
      // in sample
      ms10=_wavheader->frequency/100;
      
      
     if (_audioMap)
		 delete[] _audioMap;

     _audioMap=new ST_point[100*3600*4]; // 4 hours / 6 Megs

     
      ADM_assert(_audioMap);
     
      DIA_working *work;

      work=new DIA_working(QT_TR_NOOP("Building VBR map"));

      goTo(0);
      uint32_t Mul=2*_wavheader->channels;
      uint32_t len,sample;
      while(offset<_length)
      	{
              			work->update(offset,_length);
				if(!work->isAlive())
				{
					delete work;
					work=new DIA_working(QT_TR_NOOP("Building VBR map"));
					work->update(offset,_length);
				}
                
                		// read a packet
				if(!getPacket(internalBuffer, &len,&sample))
				{
                                    if(!index && retry)
                                    {
                                        retry--;
                                        continue;
                                    }
					printf("MapVBR:Get packet failed\n");
					break;
				}		  
			        offset+=len;
			      	rd += sample*Mul;
      				_audioMap[index].foffset=offset;
      				_audioMap[index++].woffset=rd;
         }

end:
		setpriority(PRIO_PROCESS, 0, originalPriority);

        if(!index)
        {
            delete [] _audioMap;
            _audioMap=NULL;
            _wavheader->blockalign=1152; // Mark it as VBR
            delete work;
            goTo(0);	// Purge
            printf("Build VBR failed!\n");
            return 0;
        }
      _nbMap=index;
      _wavheader->blockalign=1152; // Mark it as VBR
      printf("\n Nb entries in timeline : %lu\n",_nbMap);
      delete work;
      goTo(0);	// Purge
     return 1;
}
Exemplo n.º 18
0
/// Main function
int Master::Run()
{
    OpenSSLCrypto::threadsSetup();
    BigNumber seed1;
    seed1.SetRand(16 * 8);

    TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon)", _FULLVERSION);
    TC_LOG_INFO("server.worldserver", " ");
    TC_LOG_INFO("server.worldserver", " A World of Warcraft Cataclsym 4.3.4 Emulator  ");
    TC_LOG_INFO("server.worldserver", "       _/_/              _/          _/_/_/    _/_/    _/_/_/    _/_/_/_/  ");
    TC_LOG_INFO("server.worldserver", "    _/    _/  _/  _/_/  _/  _/    _/        _/    _/  _/    _/  _/         ");
    TC_LOG_INFO("server.worldserver", "   _/_/_/_/  _/_/      _/_/      _/        _/    _/  _/_/_/    _/_/_/      ");
    TC_LOG_INFO("server.worldserver", "  _/    _/  _/        _/  _/    _/        _/    _/  _/    _/  _/           ");
    TC_LOG_INFO("server.worldserver", " _/    _/  _/        _/    _/    _/_/_/    _/_/    _/    _/  _/_/_/_/   NG ");
    TC_LOG_INFO("server.worldserver", " Arkania Community (c) 2017!                         <http://arkania.net/> ");
    TC_LOG_INFO("server.worldserver", " ");
    TC_LOG_INFO("server.worldserver", "<Ctrl-C> to stop.\n");

    /// worldserver PID file creation
    std::string pidFile = sConfigMgr->GetStringDefault("PidFile", "");
    if (!pidFile.empty())
    {
        if (uint32 pid = CreatePIDFile(pidFile))
            TC_LOG_INFO("server.worldserver", "Daemon PID: %u\n", pid);
        else
        {
            TC_LOG_ERROR("server.worldserver", "Cannot create PID file %s.\n", pidFile.c_str());
            return 1;
        }
    }

    ///- Start the databases
    if (!_StartDB())
        return 1;

    // set server offline (not connectable)
    LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = (flag & ~%u) | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, REALM_FLAG_INVALID, realmID);

    ///- Initialize the World
    sWorld->SetInitialWorldSettings();

    ///- Initialize the signal handlers
    WorldServerSignalHandler signalINT, signalTERM;
    #ifdef _WIN32
    WorldServerSignalHandler signalBREAK;
    #endif /* _WIN32 */

    ///- Register worldserver's signal handlers
    ACE_Sig_Handler handle;
    handle.register_handler(SIGINT, &signalINT);
    handle.register_handler(SIGTERM, &signalTERM);
#ifdef _WIN32
    handle.register_handler(SIGBREAK, &signalBREAK);
#endif

    ///- Launch WorldRunnable thread
    ACE_Based::Thread worldThread(new WorldRunnable);
    worldThread.setPriority(ACE_Based::Highest);

    ACE_Based::Thread* cliThread = nullptr;

#ifdef _WIN32
    if (sConfigMgr->GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/)
#else
    if (sConfigMgr->GetBoolDefault("Console.Enable", true))
#endif
    {
        ///- Launch CliRunnable thread
        cliThread = new ACE_Based::Thread(new CliRunnable);
    }

    ACE_Based::Thread rarThread(new RARunnable);

#if defined(_WIN32) || defined(__linux__)
    
    ///- Handle affinity for multiple processors and process priority
    uint32 affinity = sConfigMgr->GetIntDefault("UseProcessors", 0);
    bool highPriority = sConfigMgr->GetBoolDefault("ProcessPriority", false);

#ifdef _WIN32 // Windows
    
    HANDLE hProcess = GetCurrentProcess();
    
    if (affinity > 0)
    {
        ULONG_PTR appAff;
        ULONG_PTR sysAff;
        
        if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
        {
            ULONG_PTR currentAffinity = affinity & appAff;            // remove non accessible processors
            
            if (!currentAffinity)
                TC_LOG_ERROR("server.worldserver", "Processors marked in UseProcessors bitmask (hex) %x are not accessible for the worldserver. Accessible processors bitmask (hex): %x", affinity, appAff);
            else if (SetProcessAffinityMask(hProcess, currentAffinity))
                TC_LOG_INFO("server.worldserver", "Using processors (bitmask, hex): %x", currentAffinity);
            else
                TC_LOG_ERROR("server.worldserver", "Can't set used processors (hex): %x", currentAffinity);
        }
    }
    
    if (highPriority)
    {
        if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS))
            TC_LOG_INFO("server.worldserver", "worldserver process priority class set to HIGH");
        else
            TC_LOG_ERROR("server.worldserver", "Can't set worldserver process priority class.");
    }
    
#else // Linux
    
    if (affinity > 0)
    {
        cpu_set_t mask;
        CPU_ZERO(&mask);

        for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i)
            if (affinity & (1 << i))
                CPU_SET(i, &mask);

        if (sched_setaffinity(0, sizeof(mask), &mask))
            TC_LOG_ERROR("server.worldserver", "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno));
        else
        {
            CPU_ZERO(&mask);
            sched_getaffinity(0, sizeof(mask), &mask);
            TC_LOG_INFO("server.worldserver", "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask));
        }
    }

    if (highPriority)
    {
        if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY))
            TC_LOG_ERROR("server.worldserver", "Can't set worldserver process priority class, error: %s", strerror(errno));
        else
            TC_LOG_INFO("server.worldserver", "worldserver process priority class set to %i", getpriority(PRIO_PROCESS, 0));
    }
    
#endif
#endif

    //Start soap serving thread
    ACE_Based::Thread* soapThread = nullptr;

    if (sConfigMgr->GetBoolDefault("SOAP.Enabled", false))
    {
        TCSoapRunnable* runnable = new TCSoapRunnable();
        runnable->SetListenArguments(sConfigMgr->GetStringDefault("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetIntDefault("SOAP.Port", 7878)));
        soapThread = new ACE_Based::Thread(runnable);
    }

    ///- Start up freeze catcher thread
    if (uint32 freezeDelay = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0))
    {
        FreezeDetectorRunnable* fdr = new FreezeDetectorRunnable();
        fdr->SetDelayTime(freezeDelay * 1000);
        ACE_Based::Thread freezeThread(fdr);
        freezeThread.setPriority(ACE_Based::Highest);
    }

    ///- Launch the world listener socket
    uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD));
    std::string bindIp = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0");

    if (sWorldSocketMgr->StartNetwork(worldPort, bindIp.c_str()) == -1)
    {
        TC_LOG_ERROR("server.worldserver", "Failed to start network");
        World::StopNow(ERROR_EXIT_CODE);
        // go down and shutdown the server
    }

    // set server online (allow connecting now)
    LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag & ~%u, population = 0 WHERE id = '%u'", REALM_FLAG_INVALID, realmID);

    TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon) ready...", _FULLVERSION);

#ifdef _DEBUG
    ASSERT(false);  // my debugging stop
#endif

    // when the main thread closes the singletons get unloaded
    // since worldrunnable uses them, it will crash if unloaded after master
    worldThread.wait();
    rarThread.wait();

    if (soapThread)
    {
        soapThread->wait();
        soapThread->destroy();
        delete soapThread;
    }

    // set server offline
    LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realmID);

    ///- Clean database before leaving
    ClearOnlineAccounts();

    _StopDB();

    TC_LOG_INFO("server.worldserver", "Halting process...");

    if (cliThread)
    {
        #ifdef _WIN32

        // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API)
        //_exit(1);
        // send keyboard input to safely unblock the CLI thread
        INPUT_RECORD b[4];
        HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
        b[0].EventType = KEY_EVENT;
        b[0].Event.KeyEvent.bKeyDown = TRUE;
        b[0].Event.KeyEvent.uChar.AsciiChar = 'X';
        b[0].Event.KeyEvent.wVirtualKeyCode = 'X';
        b[0].Event.KeyEvent.wRepeatCount = 1;

        b[1].EventType = KEY_EVENT;
        b[1].Event.KeyEvent.bKeyDown = FALSE;
        b[1].Event.KeyEvent.uChar.AsciiChar = 'X';
        b[1].Event.KeyEvent.wVirtualKeyCode = 'X';
        b[1].Event.KeyEvent.wRepeatCount = 1;

        b[2].EventType = KEY_EVENT;
        b[2].Event.KeyEvent.bKeyDown = TRUE;
        b[2].Event.KeyEvent.dwControlKeyState = 0;
        b[2].Event.KeyEvent.uChar.AsciiChar = '\r';
        b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
        b[2].Event.KeyEvent.wRepeatCount = 1;
        b[2].Event.KeyEvent.wVirtualScanCode = 0x1c;

        b[3].EventType = KEY_EVENT;
        b[3].Event.KeyEvent.bKeyDown = FALSE;
        b[3].Event.KeyEvent.dwControlKeyState = 0;
        b[3].Event.KeyEvent.uChar.AsciiChar = '\r';
        b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
        b[3].Event.KeyEvent.wVirtualScanCode = 0x1c;
        b[3].Event.KeyEvent.wRepeatCount = 1;
        DWORD numb;
        WriteConsoleInput(hStdIn, b, 4, &numb);

        cliThread->wait();

        #else

        cliThread->destroy();

        #endif

        delete cliThread;
    }

    // for some unknown reason, unloading scripts here and not in worldrunnable
    // fixes a memory leak related to detaching threads from the module
    //UnloadScriptingModule();

    OpenSSLCrypto::threadsCleanup();
    // Exit the process with specified return value
    return World::GetExitCode();
}
/**
	Rebuild frame type by actually decoding them
	to all videos loaded
	Use hurry_up flag if the codec is able to do it.

*/
uint8_t   ADM_Composer::rebuildFrameType ( void)
{
_VIDEOS *vi;
uint32_t frames=0,cur=0;
uint8_t *compBuffer=NULL;
//uint8_t *prepBuffer=NULL;
ADMImage *prepBuffer=NULL;
ADMImage *prepBufferNoCopy=NULL;
ADMImage *tmpImage=NULL;
uint32_t bframe;
aviInfo    info;
						
	if(!_nb_video)
	{
          GUI_Error_HIG(QT_TR_NOOP("No video loaded"), NULL);
		return 0;
	}
	if(!isIndexable())
	{
          GUI_Error_HIG(QT_TR_NOOP("Not indexable"),QT_TR_NOOP( "DivX 5 + packed?"));
		return 0;
	}

	uint32_t originalPriority = getpriority(PRIO_PROCESS, 0);
	uint32_t priorityLevel;

	prefs->get(PRIORITY_INDEXING,&priorityLevel);
	setpriority(PRIO_PROCESS, 0, ADM_getNiceValue(priorityLevel));

	vi=&(_videos[0]);
	vi->_aviheader->getVideoInfo (&info);
                        
	compBuffer=new uint8_t[(info.width * info.height * 3)>>1];
	ADM_assert(compBuffer);

	prepBuffer=new ADMImage(info.width ,info.height);            
    prepBufferNoCopy=new ADMImage(info.width ,info.height);      
    ADMCompressedImage img;
    img.data=compBuffer;

	ADM_assert(prepBuffer);
    ADM_assert(prepBufferNoCopy);

	for(uint32_t i=0;i<_nb_video;i++)
	{
		frames+=_videos[i]._nb_video_frames;
	}
	DIA_working *work;
        uint8_t nocopy;
	work=new DIA_working(QT_TR_NOOP("Rebuilding Frames"));


	for(uint32_t vid=0;vid<_nb_video;vid++)
	{
		// set the decoder in fast mode
			vi=&(_videos[vid]);
			vi->_aviheader->getVideoInfo (&info);
			nocopy=vi->decoder->dontcopy();
                        if(nocopy) tmpImage=prepBufferNoCopy;
                                else tmpImage=prepBuffer;
			bframe=0;
			if(vi->_reorderReady)
			{
				cur+=vi->_nb_video_frames;
			}
			else
			{
				vi->decoder->decodeHeaderOnly();
				for(uint32_t j=0;j<vi->_nb_video_frames;j++)
				{
	  				vi->_aviheader->getFrameNoAlloc (j,&img);
					if(img.dataLength)
                                        {
		    				vi->decoder->uncompress (&img, tmpImage);
                                        }
					else
						tmpImage->flags=0;
	  				vi->_aviheader->setFlag(j,tmpImage->flags);
					if(tmpImage->flags & AVI_B_FRAME)
						bframe++;

					if(work->update(cur, frames))
	  				{
						delete work;
						vi->decoder->decodeFull();
						GUI_Error_HIG(QT_TR_NOOP("Aborted"), NULL);
						delete [] compBuffer;
						delete  prepBuffer;
						delete  prepBufferNoCopy;

						setpriority(PRIO_PROCESS, 0, originalPriority);
						return 0;
       				}
					cur++;
				}
				vi->decoder->decodeFull();
				// and there is b-frame
				if(bframe)
				{
					vi->_reorderReady=vi->_aviheader->reorder();
				}
			}
	}
	delete work;
	delete [] compBuffer;
	delete  prepBuffer;
    delete  prepBufferNoCopy;

	setpriority(PRIO_PROCESS, 0, originalPriority);

	return 1;
}
Exemplo n.º 20
0
PUBLIC IxPerfProfAccStatus
ixPerfProfAccXcycleBaselineRun(
                   UINT32 *numBaselineCycle)
{
    int i,
        priority ;      /* task priority. Value is OS dependent */
    UINT32 interruptLockKey;

    UINT32 temp,
        startTime,      /* used to store start time */
        stopTime,       /* used to store stop time */
        duration;       /* difference between stop and start time */

#ifdef __vxworks
    IxOsalThread threadId;
    IX_STATUS result;
#endif

    /*error check the parameter*/
    if (NULL == numBaselineCycle)
    {
	/* report the error */ 
        IX_PERFPROF_ACC_LOG(
            IX_OSAL_LOG_LVL_ERROR, IX_OSAL_LOG_DEV_STDERR,
            "ixPerfProfAccXcycleBaselineRun - numBaselineCycle is invalid\n",
            0, 0, 0, 0, 0, 0);
	/* return error */
        return IX_PERFPROF_ACC_STATUS_FAIL;
    }

    if (IX_PERFPROF_ACC_STATUS_ANOTHER_UTIL_IN_PROGRESS
        == ixPerfProfAccLock())
    {
        return IX_PERFPROF_ACC_STATUS_ANOTHER_UTIL_IN_PROGRESS;
    }

    /*
     * If the tool is running, then do not allow baselining to progress
     */
    if (ixPerfProfAccXcycleMeasurementInProgress)
    {
        ixPerfProfAccUnlock();
        return IX_PERFPROF_ACC_STATUS_XCYCLE_MEASUREMENT_IN_PROGRESS;
    }

    /*
     * Find out how many loops is needed to to complete
     * 1/IX_PERFPROF_ACC_XCYCLE_TIME_SLICES_PER_SEC seconds
     */
    ixNumLoopPerTimeSlice= ixPerfProfAccXcycleComputeLoopsPerSlice();

    /*
     * Disable interrupts so that no ISR can run. We get all the CPU
     * cycles.
     */
    interruptLockKey = ixOsalIrqLock();

#ifdef __linuxapp
    priority = getpriority(PRIO_PROCESS,0);
    if(0 != setpriority( PRIO_PROCESS, 0,
            IX_PERFPROF_ACC_XCYCLE_LINUXAPP_PRIORITY_HIGHEST )
            )
    {
        ixPerfProfAccUnlock();
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_SET_FAIL;
    }

#else

    result = ixOsalThreadIdGet (&threadId);
    if (IX_SUCCESS != result)
    {
        ixPerfProfAccUnlock();
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_SET_FAIL;
    }
    taskPriorityGet (threadId, &priority);
    result = ixOsalThreadPrioritySet (
            &threadId,
            IX_PERFPROF_ACC_XCYCLE_VXWORKS_PRIORITY_HIGHEST );
    if (IX_SUCCESS != result)
    {
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_SET_FAIL;
    }
#endif

    /*
     * Perform a measure of time needed for one measurement without
     * load.
     */
    startTime = ixPerfProfAccXcycleApbTimerGet();
    for (i = 0; IX_PERFPROF_ACC_XCYCLE_TIME_SLICES_PER_SEC > i; i++)
    {
        temp = ixNumLoopPerTimeSlice;
        ixPerfProfAccXcycleLoopIter(temp);
    }
    stopTime = ixPerfProfAccXcycleApbTimerGet();

    /*
     * Rollover situation is handled through the fact that the different
     * between start and stop time is a fraction of 32bit storage
     * The duration of time stored in 32 bits is 65 sec
     * We expect difference between start and stop time to be
     * ~ 1 sec
     */
    duration = stopTime - startTime;

    ixOsalIrqUnlock(interruptLockKey);

#ifdef __linuxapp
    if(setpriority(PRIO_PROCESS, 0, priority) != 0)
    {
        ixPerfProfAccUnlock();
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_RESTORE_FAIL;
    }
#else /* ifdef __linuxapp */
    /*
     * Restore the calling thread to previous priority
     */
    result = ixOsalThreadPrioritySet (&threadId, priority);

    if (IX_SUCCESS != result)
    {
        ixPerfProfAccUnlock();
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_RESTORE_FAIL;
    }

#endif /* ifdef __linuxapp */

    ixPerfProfAccXcycleCurrentBaseline = duration;
    *numBaselineCycle = duration;
    ixPerfProfAccUnlock();
    return IX_PERFPROF_ACC_STATUS_SUCCESS ;
} /* end of ixPerfProfAccXcycleBaselineRun() */
Exemplo n.º 21
0
void *http_server (void *arg)
{
int                 rc;                 /* Return code               */
int                 lsock;              /* Socket for listening      */
int                 csock;              /* Socket for conversation   */
struct sockaddr_in  server;             /* Server address structure  */
fd_set              selset;             /* Read bit map for select   */
int                 optval;             /* Argument for setsockopt   */
TID                 httptid;            /* Negotiation thread id     */
struct timeval      timeout;            /* timeout value             */


    UNREFERENCED(arg);

    http_serv.httpshutdown = TRUE;

    hdl_adsc("http_shutdown",http_shutdown, NULL);

    /* Set root mode in order to set priority */
    SETMODE(ROOT);

    /* Set server thread priority; ignore any errors */
    if(setpriority(PRIO_PROCESS, 0, sysblk.srvprio))
       WRMSG(HHC00136, "W", "setpriority()", strerror(errno));

    /* Back to user mode */
    SETMODE(USER);

    /* Display thread started message on control panel */
    WRMSG (HHC00100, "I", (u_long)thread_id(), getpriority(PRIO_PROCESS,0), "HTTP server");

    /* make sure root path is built */
    if ( http_root() == NULL )
        goto http_server_stop;

    /* Obtain a socket */
    lsock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (lsock < 0)
    {
        WRMSG(HHC01800,"E", "socket()", strerror(HSO_errno));
        goto http_server_stop;
    }

    /* Allow previous instance of socket to be reused */
    optval = 1;
    setsockopt (lsock, SOL_SOCKET, SO_REUSEADDR,
                (void*)&optval, sizeof(optval));

    /* Prepare the sockaddr structure for the bind */
    memset (&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = http_serv.httpport;
    server.sin_port = htons(server.sin_port);

    http_serv.httpbinddone = FALSE;
    /* Attempt to bind the socket to the port */
    while (TRUE)
    {
        rc = bind (lsock, (struct sockaddr *)&server, sizeof(server));

        if (rc == 0 || HSO_errno != HSO_EADDRINUSE) break;

        WRMSG(HHC01804, "W", http_serv.httpport);
        SLEEP(10);
    } /* end while */

    if (rc != 0)
    {
        WRMSG(HHC01800,"E", "bind()", strerror(HSO_errno));
        goto http_server_stop;
    }
    else
        http_serv.httpbinddone = TRUE;

    /* Put the socket into listening state */
    rc = listen (lsock, 32);

    if (rc < 0)
    {
        WRMSG(HHC01800,"E", "listen()", strerror(HSO_errno));
        http_serv.httpbinddone = FALSE;
        goto http_server_stop;
    }

    http_serv.httpshutdown = FALSE;

    WRMSG(HHC01803, "I", http_serv.httpport);

    /* Handle http requests */
    while ( !http_serv.httpshutdown )
    {

        /* Initialize the select parameters */
        FD_ZERO (&selset);
        FD_SET (lsock, &selset);

        timeout.tv_sec  = 0;
        timeout.tv_usec = 10000;

        /* until a better way to implement this use standard windows */
#undef select
        /* Wait for a file descriptor to become ready  use NON-BLOCKING select()*/
        rc = select ( lsock+1, &selset, NULL, NULL, &timeout );

        if ( rc == 0 || http_serv.httpshutdown ) continue;

        if (rc < 0 )
        {
            if (HSO_errno == HSO_EINTR) continue;
            WRMSG(HHC01800, "E", "select()", strerror(HSO_errno));
            break;
        }

        /* If a http request has arrived then accept it */
        if (FD_ISSET(lsock, &selset))
        {
            /* Accept the connection and create conversation socket */
            csock = accept (lsock, NULL, NULL);

            if (csock < 0)
            {
                WRMSG(HHC01800, "E", "accept()", strerror(HSO_errno));
                continue;
            }

            /* Create a thread to execute the http request */
            rc = create_thread (&httptid, DETACHED,
                                http_request, (void *)(uintptr_t)csock,
                                "http_request");
            if(rc)
            {
                WRMSG(HHC00102, "E", strerror(rc));
                close_socket (csock);
            }

        } /* end if(lsock) */

    } /* end while */

    /* Close the listening socket */
    close_socket (lsock);

http_server_stop:
    if ( !sysblk.shutdown )
        hdl_rmsc(http_shutdown, NULL);

    /* Display thread started message on control panel */
    WRMSG(HHC00101, "I", (u_long)thread_id(), getpriority(PRIO_PROCESS,0), "HTTP server");

    sysblk.httptid = 0;

    http_serv.httpbinddone = FALSE;

    signal_condition(&http_serv.http_wait_shutdown);

    return NULL;

} /* end function http_server */
Exemplo n.º 22
0
PUBLIC IxPerfProfAccStatus
ixPerfProfAccXcycleStart (UINT32 numMeasurementsRequested)
{

#ifdef __linuxapp
    UINT32 result;      /* result of thread creation */
    int priority;       /* used to remember priority of current process */
    pthread_attr_t threadAttribute; /* used to setup thread attribute */
#elif defined (__vxworks)
    IxOsalThreadAttr threadAttr;
    IX_STATUS retStatus;
#endif /* ifdef __linuxapp */

    ixPerfProfAccXcycleStopMeasurement = FALSE;

    /*
     * Check if baseline had been run. If not, terminate.
     */
    if (0 == ixPerfProfAccXcycleCurrentBaseline)
    {
        return IX_PERFPROF_ACC_STATUS_XCYCLE_NO_BASELINE;
    }

    /*
     * Range checking for numMeasurementsRequested
     */
    if (IX_PERFPROF_ACC_XCYCLE_MAX_NUM_OF_MEASUREMENTS < numMeasurementsRequested)
    {
        return IX_PERFPROF_ACC_STATUS_XCYCLE_MEASUREMENT_REQUEST_OUT_OF_RANGE;
    }

    /*
     * Check if Xcycle is already running, do not allow another start
     * if Xcycle is running.
     */
    if (ixPerfProfAccXcycleMeasurementInProgress)
    {
        return IX_PERFPROF_ACC_STATUS_XCYCLE_MEASUREMENT_IN_PROGRESS;
    }

    /*
     * Xcycle is not running, set the flag to indicate that
     * a measurement is in progress
     */
    else
    {
        ixPerfProfAccXcycleMeasurementInProgress = TRUE ;
    }

    /*
     * Check to see if any other PMU utilities besides Xcycle is running
     * If yes, we abort to avoid inaccurate results due to load introduce
     * by other tools.
     */
    if (IX_PERFPROF_ACC_STATUS_ANOTHER_UTIL_IN_PROGRESS
        == ixPerfProfAccLock())
    {
        return IX_PERFPROF_ACC_STATUS_ANOTHER_UTIL_IN_PROGRESS;
    }

#ifdef __linuxapp
    /*
     * Set current priority to lowest possible
     */
    priority = getpriority(PRIO_PROCESS,0);
    if(0 != setpriority (PRIO_PROCESS,
                         0,
                         IX_PERFPROF_ACC_XCYCLE_LINUXAPP_PRIORITY_LOWEST))
    {
        ixPerfProfAccUnlock();
        ixPerfProfAccXcycleMeasurementInProgress = FALSE ;
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_SET_FAIL;
    }

    /*
     * Preparing to create a new thread of ixPerfProfAccXcycleNumPeriodRun()
     * Start with setting thread attribute with state DETACHED
     */
    result = pthread_attr_init (&threadAttribute);
    result |= pthread_attr_setdetachstate (&threadAttribute,
                                            PTHREAD_CREATE_DETACHED);
    result |= pthread_create (&xcycleThreadId,
                            &threadAttribute,
                            (void *) &ixPerfProfAccXcycleNumPeriodRun ,
                            (void *)numMeasurementsRequested);
    if (0 != result)
    {
        ixPerfProfAccUnlock();
        ixPerfProfAccXcycleMeasurementInProgress = FALSE ;
        return  IX_PERFPROF_ACC_STATUS_XCYCLE_THREAD_CREATE_FAIL;
    }/* end of if (result) */

    /*
     * Successful in creating a new thread with lowest priority.
     * Restore priority of calling thread to original level
     */
    if (0 != setpriority (PRIO_PROCESS, 0, priority))
    {
        ixPerfProfAccUnlock();
        return IX_PERFPROF_ACC_STATUS_XCYCLE_PRIORITY_SET_FAIL;
    }
#else /* ifdef __linuxapp */

    /*
     * Create a new thread of ixPerfProfAccXcycleNumPeriodRun()
     * Set the priority level of new thread to lowest possible
     * If fail, set ixPerfProfAccXcycleMeasurementInProgress
     * back to FALSE and return error.
     */
    threadAttr.name = "PerfProf Xcycle thread";
    threadAttr.stackSize = 0;
    threadAttr.priority = IX_PERFPROF_ACC_XCYCLE_VXWORKS_PRIORITY_LOWEST;
    if ((retStatus = ixOsalThreadCreate(
	           &xcycleThreadId,
		   &threadAttr, 
		   (IxOsalVoidFnVoidPtr) ixPerfProfAccXcycleNumPeriodRun,
		   (void*) numMeasurementsRequested)) ==
	  IX_SUCCESS)

    {
	if ((retStatus = ixOsalThreadStart(&xcycleThreadId)) != IX_SUCCESS)
	{
	    ixPerfProfAccUnlock();
	    ixPerfProfAccXcycleMeasurementInProgress = FALSE;
	    return  IX_PERFPROF_ACC_STATUS_XCYCLE_THREAD_CREATE_FAIL;
	}
    }	
    else
    {
        ixPerfProfAccUnlock();
        ixPerfProfAccXcycleMeasurementInProgress = FALSE ;
        return  IX_PERFPROF_ACC_STATUS_XCYCLE_THREAD_CREATE_FAIL;
    } /* end of if (result) */

#endif /* ifdef __linuxapp */

    return IX_PERFPROF_ACC_STATUS_SUCCESS;
} /* end of ixPerfProfAccXcycleStart() */
Exemplo n.º 23
0
int
main(int ac, char **av)
{
	int lc;			/* loop counter */
	char *msg;		/* message returned from parse_opts */
	int ind;		/* counter variable for test case looping */
	char *test_desc; 	/* test specific error message */
	int which;		/* process priority category */
	uid_t who;		/* process uid of the test process */
    
	/* Parse standard options given to run the test. */
	msg = parse_opts(ac, av, (option_t *) NULL, NULL);
	if (msg != (char *) NULL) {
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
		tst_exit();
	}

	/* Perform global setup for test */
	setup();

	/* set the expected errnos... */
	TEST_EXP_ENOS(exp_enos);

	/* Check looping state if -i option given */
	for (lc = 0; TEST_LOOPING(lc); lc++) {
		/* Reset Tst_count in case we are looping. */
		Tst_count=0;

		for (ind = 0; ind < TST_TOTAL; ind++) {
			which = Test_cases[ind].pro_which;
			who = Test_cases[ind].pro_uid;
			test_desc = Test_cases[ind].desc;

			if (who == 0) {
				/* Get the actual uid of the process */
				who = getuid();
			}

			/* 
			 * Invoke getpriority with the specified
			 * 'which' and 'who' arguments and verify
			 * that it fails with expected errno.
			 */
			TEST(getpriority(which, who));

			/* check return code from getpriority(2) */
			if (TEST_RETURN < 0) {
				TEST_ERROR_LOG(TEST_ERRNO);
				if (TEST_ERRNO == Test_cases[ind].exp_errno) {
					tst_resm(TPASS, "getpriority(2) fails, "
						 "%s, errno:%d",
						 test_desc, TEST_ERRNO);
				} else {
					tst_resm(TFAIL, "getpriority() fails, "
						 "%s, errno:%d, expected errno:"
						 "%d", test_desc, TEST_ERRNO,
						 Test_cases[ind].exp_errno);
				}
			} else {
				tst_resm(TFAIL, "getpriority() returned %d, "
					 "expected -1, errno:%d", TEST_RETURN,
					 Test_cases[ind].exp_errno);
			}
		}	/* End of TEST CASE LOOPING. */

	}	/* End for TEST_LOOPING */

	/* Call cleanup() to undo setup done for the test. */
	cleanup();

	/*NOTREACHED*/
	return(0);
}	/* End main */
Exemplo n.º 24
0
	void
	threadMain() {
		while (!boost::this_thread::interruption_requested()) {
			syscalls::sleep(60 * 60);

			begin_touch:

			boost::this_thread::disable_interruption di;
			boost::this_thread::disable_syscall_interruption dsi;
			// Fork a process which touches everything in the server instance dir.
			pid_t pid = syscalls::fork();
			if (pid == 0) {
				// Child
				int prio, ret, e;

				closeAllFileDescriptors(2);

				// Make process nicer.
				do {
					prio = getpriority(PRIO_PROCESS, getpid());
				} while (prio == -1 && errno == EINTR);
				if (prio != -1) {
					prio++;
					if (prio > 20) {
						prio = 20;
					}
					do {
						ret = setpriority(PRIO_PROCESS, getpid(), prio);
					} while (ret == -1 && errno == EINTR);
				} else {
					perror("getpriority");
				}

				do {
					ret = chdir(wo->instanceDir->getPath().c_str());
				} while (ret == -1 && errno == EINTR);
				if (ret == -1) {
					e = errno;
					fprintf(stderr, "chdir(\"%s\") failed: %s (%d)\n",
						wo->instanceDir->getPath().c_str(),
						strerror(e), e);
					fflush(stderr);
					_exit(1);
				}
				restoreOomScore(agentsOptions);

				execlp("/bin/sh", "/bin/sh", "-c", "find . | xargs touch", (char *) 0);
				e = errno;
				fprintf(stderr, "Cannot execute 'find . | xargs touch': %s (%d)\n",
					strerror(e), e);
				fflush(stderr);
				_exit(1);
			} else if (pid == -1) {
				// Error
				P_WARN("Could not touch the server instance directory because "
					"fork() failed. Retrying in 2 minutes...");
				boost::this_thread::restore_interruption si(di);
				boost::this_thread::restore_syscall_interruption rsi(dsi);
				syscalls::sleep(60 * 2);
				goto begin_touch;
			} else {
				syscalls::waitpid(pid, NULL, 0);
			}
		}
	}
Exemplo n.º 25
0
/*
 * hourly_stats - print some interesting stats
 */
void
write_stats(void)
{
	FILE	*fp;
	double	ftemp;
#ifdef DOSYNCTODR
	struct timeval tv;
#if !defined(VMS)
	int	prio_set;
#endif
#ifdef HAVE_GETCLOCK
        struct timespec ts;
#endif
	int	o_prio;

	/*
	 * Sometimes having a Sun can be a drag.
	 *
	 * The kernel variable dosynctodr controls whether the system's
	 * soft clock is kept in sync with the battery clock. If it
	 * is zero, then the soft clock is not synced, and the battery
	 * clock is simply left to rot. That means that when the system
	 * reboots, the battery clock (which has probably gone wacky)
	 * sets the soft clock. That means ntpd starts off with a very
	 * confused idea of what time it is. It then takes a large
	 * amount of time to figure out just how wacky the battery clock
	 * has made things drift, etc, etc. The solution is to make the
	 * battery clock sync up to system time. The way to do THAT is
	 * to simply set the time of day to the current time of day, but
	 * as quickly as possible. This may, or may not be a sensible
	 * thing to do.
	 *
	 * CAVEAT: settimeofday() steps the sun clock by about 800 us,
	 *         so setting DOSYNCTODR seems a bad idea in the
	 *         case of us resolution
	 */

#if !defined(VMS)
	/*
	 * (prr) getpriority returns -1 on error, but -1 is also a valid
	 * return value (!), so instead we have to zero errno before the
	 * call and check it for non-zero afterwards.
	 */
	errno = 0;
	prio_set = 0;
	o_prio = getpriority(PRIO_PROCESS,0); /* Save setting */

	/*
	 * (prr) if getpriority succeeded, call setpriority to raise
	 * scheduling priority as high as possible.  If that succeeds
	 * as well, set the prio_set flag so we remember to reset
	 * priority to its previous value below.  Note that on Solaris
	 * 2.6 (and beyond?), both getpriority and setpriority will fail
	 * with ESRCH, because sched_setscheduler (called from main) put
	 * us in the real-time scheduling class which setpriority
	 * doesn't know about. Being in the real-time class is better
	 * than anything setpriority can do, anyhow, so this error is
	 * silently ignored.
	 */
	if ((errno == 0) && (setpriority(PRIO_PROCESS,0,-20) == 0))
		prio_set = 1;	/* overdrive */
#endif /* VMS */
#ifdef HAVE_GETCLOCK
        (void) getclock(TIMEOFDAY, &ts);
        tv.tv_sec = ts.tv_sec;
        tv.tv_usec = ts.tv_nsec / 1000;
#else /*  not HAVE_GETCLOCK */
	GETTIMEOFDAY(&tv,(struct timezone *)NULL);
#endif /* not HAVE_GETCLOCK */
	if (ntp_set_tod(&tv,(struct timezone *)NULL) != 0)
		msyslog(LOG_ERR, "can't sync battery time: %m");
#if !defined(VMS)
	if (prio_set)
		setpriority(PRIO_PROCESS, 0, o_prio); /* downshift */
#endif /* VMS */
#endif /* DOSYNCTODR */
	record_sys_stats();
	ftemp = fabs(prev_drift_comp - drift_comp); 
	prev_drift_comp = drift_comp;
	if (ftemp > clock_phi)
		return;

	if (stats_drift_file != 0 && drift_file_sw) {

		/*
		 * When the frequency file is written, initialize the
		 * wander threshold to a configured initial value.
		 * Thereafter reduce it by a factor of 0.5. When it
		 * drops below the frequency wander, write the frequency
		 * file. This adapts to the prevailing wander yet
		 * minimizes the file writes.
		 */
		drift_file_sw = FALSE;
		wander_resid *= 0.5;
#ifdef DEBUG
		if (debug)
			printf("write_stats: wander %.6lf thresh %.6lf, freq %.6lf\n",
			    clock_stability * 1e6, wander_resid * 1e6,
			    drift_comp * 1e6);
#endif
 		if (sys_leap != LEAP_NOTINSYNC && clock_stability >
		    wander_resid) {
			wander_resid = wander_threshold;
			if ((fp = fopen(stats_temp_file, "w")) == NULL)
			    {
				msyslog(LOG_ERR,
				    "frequency file %s: %m",
				    stats_temp_file);
				return;
			}
			fprintf(fp, "%.3f\n", drift_comp * 1e6);
			(void)fclose(fp);
			/* atomic */
#ifdef SYS_WINNT
			if (_unlink(stats_drift_file)) /* rename semantics differ under NT */
				msyslog(LOG_WARNING, 
					"Unable to remove prior drift file %s, %m", 
					stats_drift_file);
#endif /* SYS_WINNT */

#ifndef NO_RENAME
			if (rename(stats_temp_file, stats_drift_file))
				msyslog(LOG_WARNING, 
					"Unable to rename temp drift file %s to %s, %m", 
					stats_temp_file, stats_drift_file);
#else
			/* we have no rename NFS of ftp in use */
			if ((fp = fopen(stats_drift_file, "w")) ==
			    NULL) {
				msyslog(LOG_ERR,
				    "frequency file %s: %m",
				    stats_drift_file);
				return;
			}
#endif

#if defined(VMS)
			/* PURGE */
			{
				$DESCRIPTOR(oldvers,";-1");
				struct dsc$descriptor driftdsc = {
					strlen(stats_drift_file), 0, 0,
					    stats_drift_file };
				while(lib$delete_file(&oldvers,
				    &driftdsc) & 1);
			}
#endif
		} else {
			/* XXX: Log a message at INFO level */
		}
	}
}
Exemplo n.º 26
0
static int
getentropy_fallback(void *buf, size_t len)
{
	uint8_t results[SHA512_DIGEST_LENGTH];
	int save_errno = errno, e, pgs = sysconf(_SC_PAGESIZE), faster = 0, repeat;
	static int cnt;
	struct timespec ts;
	struct timeval tv;
	perfstat_cpu_total_t cpustats;
#ifdef _AIX61
	perfstat_cpu_total_wpar_t cpustats_wpar;
#endif
	perfstat_partition_total_t lparstats;
	perfstat_disk_total_t diskinfo;
	perfstat_netinterface_total_t netinfo;
	struct rusage ru;
	sigset_t sigset;
	struct stat st;
	SHA512_CTX ctx;
	static pid_t lastpid;
	pid_t pid;
	size_t i, ii, m;
	char *p;

	pid = getpid();
	if (lastpid == pid) {
		faster = 1;
		repeat = 2;
	} else {
		faster = 0;
		lastpid = pid;
		repeat = REPEAT;
	}
	for (i = 0; i < len; ) {
		int j;
		SHA512_Init(&ctx);
		for (j = 0; j < repeat; j++) {
			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
			if (e != -1) {
				cnt += (int)tv.tv_sec;
				cnt += (int)tv.tv_usec;
			}

			HX(perfstat_cpu_total(NULL, &cpustats,
			    sizeof(cpustats), 1) == -1, cpustats);

#ifdef _AIX61
			HX(perfstat_cpu_total_wpar(NULL, &cpustats_wpar,
			    sizeof(cpustats_wpar), 1) == -1, cpustats_wpar);
#endif

			HX(perfstat_partition_total(NULL, &lparstats,
			    sizeof(lparstats), 1) == -1, lparstats);

			HX(perfstat_disk_total(NULL, &diskinfo,
			    sizeof(diskinfo), 1) == -1, diskinfo);

			HX(perfstat_netinterface_total(NULL, &netinfo,
			    sizeof(netinfo), 1) == -1, netinfo);

			for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]); ii++)
				HX(clock_gettime(cl[ii], &ts) == -1, ts);

			HX((pid = getpid()) == -1, pid);
			HX((pid = getsid(pid)) == -1, pid);
			HX((pid = getppid()) == -1, pid);
			HX((pid = getpgid(0)) == -1, pid);
			HX((e = getpriority(0, 0)) == -1, e);

			if (!faster) {
				ts.tv_sec = 0;
				ts.tv_nsec = 1;
				(void) nanosleep(&ts, NULL);
			}

			HX(sigpending(&sigset) == -1, sigset);
			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
			    sigset);

			HF(getentropy);	/* an addr in this library */
			HF(printf);		/* an addr in libc */
			p = (char *)&p;
			HD(p);		/* an addr on stack */
			p = (char *)&errno;
			HD(p);		/* the addr of errno */

			if (i == 0) {
				struct sockaddr_storage ss;
				struct statvfs stvfs;
				struct termios tios;
				socklen_t ssl;
				off_t off;

				/*
				 * Prime-sized mappings encourage fragmentation;
				 * thus exposing some address entropy.
				 */
				struct mm {
					size_t	npg;
					void	*p;
				} mm[] =	 {
					{ 17, MAP_FAILED }, { 3, MAP_FAILED },
					{ 11, MAP_FAILED }, { 2, MAP_FAILED },
					{ 5, MAP_FAILED }, { 3, MAP_FAILED },
					{ 7, MAP_FAILED }, { 1, MAP_FAILED },
					{ 57, MAP_FAILED }, { 3, MAP_FAILED },
					{ 131, MAP_FAILED }, { 1, MAP_FAILED },
				};

				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
					HX(mm[m].p = mmap(NULL,
					    mm[m].npg * pgs,
					    PROT_READ|PROT_WRITE,
					    MAP_PRIVATE|MAP_ANON, -1,
					    (off_t)0), mm[m].p);
					if (mm[m].p != MAP_FAILED) {
						size_t mo;

						/* Touch some memory... */
						p = mm[m].p;
						mo = cnt %
						    (mm[m].npg * pgs - 1);
						p[mo] = 1;
						cnt += (int)((long)(mm[m].p)
						    / pgs);
					}

					/* Check cnts and times... */
					for (ii = 0; ii < sizeof(cl)/sizeof(cl[0]);
					    ii++) {
						HX((e = clock_gettime(cl[ii],
						    &ts)) == -1, ts);
						if (e != -1)
							cnt += (int)ts.tv_nsec;
					}

					HX((e = getrusage(RUSAGE_SELF,
					    &ru)) == -1, ru);
					if (e != -1) {
						cnt += (int)ru.ru_utime.tv_sec;
						cnt += (int)ru.ru_utime.tv_usec;
					}
				}

				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
					if (mm[m].p != MAP_FAILED)
						munmap(mm[m].p, mm[m].npg * pgs);
					mm[m].p = MAP_FAILED;
				}

				HX(stat(".", &st) == -1, st);
				HX(statvfs(".", &stvfs) == -1, stvfs);

				HX(stat("/", &st) == -1, st);
				HX(statvfs("/", &stvfs) == -1, stvfs);

				HX((e = fstat(0, &st)) == -1, st);
				if (e == -1) {
					if (S_ISREG(st.st_mode) ||
					    S_ISFIFO(st.st_mode) ||
					    S_ISSOCK(st.st_mode)) {
						HX(fstatvfs(0, &stvfs) == -1,
						    stvfs);
						HX((off = lseek(0, (off_t)0,
						    SEEK_CUR)) < 0, off);
					}
					if (S_ISCHR(st.st_mode)) {
						HX(tcgetattr(0, &tios) == -1,
						    tios);
					} else if (S_ISSOCK(st.st_mode)) {
						memset(&ss, 0, sizeof ss);
						ssl = sizeof(ss);
						HX(getpeername(0,
						    (void *)&ss, &ssl) == -1,
						    ss);
					}
				}

				HX((e = getrusage(RUSAGE_CHILDREN,
				    &ru)) == -1, ru);
				if (e != -1) {
					cnt += (int)ru.ru_utime.tv_sec;
					cnt += (int)ru.ru_utime.tv_usec;
				}
			} else {
				/* Subsequent hashes absorb previous result */
				HD(results);
			}

			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
			if (e != -1) {
				cnt += (int)tv.tv_sec;
				cnt += (int)tv.tv_usec;
			}

			HD(cnt);
		}
		SHA512_Final(results, &ctx);
		memcpy((char *)buf + i, results, min(sizeof(results), len - i));
		i += min(sizeof(results), len - i);
	}
	explicit_bzero(&ctx, sizeof ctx);
	explicit_bzero(results, sizeof results);
	if (gotdata(buf, len) == 0) {
		errno = save_errno;
		return 0;		/* satisfied */
	}
	errno = EIO;
	return -1;
}
Exemplo n.º 27
0
/*---------------------------------------------------------------------------*/
static void* hao_thread(void* dummy)
{
  char*  msgbuf  = NULL;
  int    msgidx  = -1;
  int    msgamt  = 0;
  char*  msgend  = NULL;
  char   svchar  = 0;
  int    bufamt  = 0;

  UNREFERENCED(dummy);

  /* Do not start HAO if no logger is active 
   * the next hao command will restart the thread
   */
  if(!logger_status())
  {
    haotid = 0;
    return NULL;
  }

  WRMSG(HHC00100, "I", (u_long)thread_id(), getpriority(PRIO_PROCESS,0), "Hercules Automatic Operator");

  /* Wait for panel thread to engage */
  /* Do until shutdown */
  while(!sysblk.shutdown && msgamt >= 0)
  {
    /* wait for message data */
    msgamt = log_read(&msgbuf, &msgidx, LOG_BLOCK);
    if(msgamt > 0)
    {
      /* append to existing data */
      if(msgamt > (int)((sizeof(ao_msgbuf) - 1) - bufamt))
        msgamt = (int)((sizeof(ao_msgbuf) - 1) - bufamt);
      strncpy( &ao_msgbuf[bufamt], msgbuf, msgamt );
      ao_msgbuf[bufamt += msgamt] = 0;
      msgbuf = ao_msgbuf;

      /* process only complete messages */
      msgend = strchr(msgbuf,'\n');
      while(msgend)
      {
        /* null terminate message */
        svchar = *(msgend+1);
        *(msgend+1) = 0;

        /* process message */
        hao_message(msgbuf);

        /* restore destroyed byte */
        *(msgend+1) = svchar;
        msgbuf = msgend+1;
        msgend = strchr(msgbuf,'\n');
      }

      /* shift message buffer */
      memmove( ao_msgbuf, msgbuf, bufamt -= (msgbuf - ao_msgbuf) );
    }
  }

  WRMSG(HHC00101, "I", (u_long)thread_id(), getpriority(PRIO_PROCESS,0), "Hercules Automatic Operator");
  return NULL;
}
Exemplo n.º 28
0
int main(int argc,char **argv, char **envp)
{
  struct plugins_list_entry *list;
  char config_file[SRVBUFLEN];
  int logf;

  /* getopt() stuff */
  extern char *optarg;
  extern int optind, opterr, optopt;
  int errflag, cp;

#if defined HAVE_MALLOPT
  mallopt(M_CHECK_ACTION, 0);
#endif

  umask(077);
  compute_once();

  memset(cfg_cmdline, 0, sizeof(cfg_cmdline));
  memset(&config, 0, sizeof(struct configuration));
  memset(&config_file, 0, sizeof(config_file));

  log_notifications_init(&log_notifications);
  config.acct_type = ACCT_PMBGP;

  find_id_func = NULL;
  plugins_list = NULL;
  errflag = 0;
  rows = 0;

  /* getting commandline values */
  while (!errflag && ((cp = getopt(argc, argv, ARGS_PMBGPD)) != -1)) {
    cfg_cmdline[rows] = malloc(SRVBUFLEN);
    switch (cp) {
    case 'L':
      strlcpy(cfg_cmdline[rows], "bgp_daemon_ip: ", SRVBUFLEN);
      strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows]));
      rows++;
      break;
    case 'l':
      strlcpy(cfg_cmdline[rows], "bgp_daemon_port: ", SRVBUFLEN);
      strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows]));
      rows++;
      break;
    case 'D':
      strlcpy(cfg_cmdline[rows], "daemonize: true", SRVBUFLEN);
      rows++;
      break;
    case 'd':
      debug = TRUE;
      strlcpy(cfg_cmdline[rows], "debug: true", SRVBUFLEN);
      rows++;
      break;
    case 'f':
      strlcpy(config_file, optarg, sizeof(config_file));
      break;
    case 'F':
      strlcpy(cfg_cmdline[rows], "pidfile: ", SRVBUFLEN);
      strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows]));
      rows++;
      break;
    case 'S':
      strlcpy(cfg_cmdline[rows], "syslog: ", SRVBUFLEN);
      strncat(cfg_cmdline[rows], optarg, CFG_LINE_LEN(cfg_cmdline[rows]));
      rows++;
      break;
    case 'h':
      usage_daemon(argv[0]);
      exit(0);
      break;
    case 'V':
      version_daemon(PMBGPD_USAGE_HEADER);
      exit(0);
      break;
    default:
      usage_daemon(argv[0]);
      exit(1);
      break;
    }
  }


  /* post-checks and resolving conflicts */
  if (strlen(config_file)) {
    if (parse_configuration_file(config_file) != SUCCESS)
      exit(1);
  }
  else {
    if (parse_configuration_file(NULL) != SUCCESS)
      exit(1);
  }

  list = plugins_list;
  while (list) {
    list->cfg.acct_type = ACCT_PMBGP;
    set_default_preferences(&list->cfg);
    if (!strcmp(list->type.string, "core")) {
      memcpy(&config, &list->cfg, sizeof(struct configuration));
      config.name = list->name;
      config.type = list->type.string;
    }
    list = list->next;
  }

  if (config.files_umask) umask(config.files_umask);

  if (config.daemon) {
    if (debug || config.debug)
      printf("WARN ( %s/core ): debug is enabled; forking in background. Logging to standard error (stderr) will get lost.\n", config.name);
    daemonize();
  }

  initsetproctitle(argc, argv, envp);
  if (config.syslog) {
    logf = parse_log_facility(config.syslog);
    if (logf == ERR) {
      config.syslog = NULL;
      printf("WARN ( %s/core ): specified syslog facility is not supported. Logging to standard error (stderr).\n", config.name);
    }
    else openlog(NULL, LOG_PID, logf);
    Log(LOG_INFO, "INFO ( %s/core ): Start logging ...\n", config.name);
  }

  if (config.logfile)
  {
    config.logfile_fd = open_output_file(config.logfile, "a", FALSE);
    while (list) {
      list->cfg.logfile_fd = config.logfile_fd ;
      list = list->next;
    }
  }

  if (config.proc_priority) {
    int ret;

    ret = setpriority(PRIO_PROCESS, 0, config.proc_priority);
    if (ret) Log(LOG_WARNING, "WARN ( %s/core ): proc_priority failed (errno: %d)\n", config.name, errno);
    else Log(LOG_INFO, "INFO ( %s/core ): proc_priority set to %d\n", config.name, getpriority(PRIO_PROCESS, 0));
  }

  if (strlen(config_file)) {
    char canonical_path[PATH_MAX], *canonical_path_ptr;

    canonical_path_ptr = realpath(config_file, canonical_path);
    if (canonical_path_ptr) Log(LOG_INFO, "INFO ( %s/core ): Reading configuration file '%s'.\n", config.name, canonical_path);
  }
  else Log(LOG_INFO, "INFO ( %s/core ): Reading configuration from cmdline.\n", config.name);

  pm_setproctitle("%s [%s]", "Core Process", config.proc_name);
  if (config.pidfile) write_pid_file(config.pidfile);

  /* signal handling we want to inherit to plugins (when not re-defined elsewhere) */
  signal(SIGCHLD, startup_handle_falling_child); /* takes note of plugins failed during startup phase */
  signal(SIGHUP, reload); /* handles reopening of syslog channel */
  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, reload_maps); /* sets to true the reload_maps flag */
  signal(SIGPIPE, SIG_IGN); /* we want to exit gracefully when a pipe is broken */
  signal(SIGINT, my_sigint_handler);
  signal(SIGTERM, my_sigint_handler);

  if (!config.nfacctd_bgp) config.nfacctd_bgp = BGP_DAEMON_ONLINE;
  if (!config.nfacctd_bgp_port) config.nfacctd_bgp_port = BGP_TCP_PORT;

  bgp_prepare_daemon();
  skinny_bgp_daemon();
}
Exemplo n.º 29
0
// nice command implementation
void executeNice(Cmd c)
{
	int which, who, priority;
	int setCommand = 0;		
	if(c->args[1]!=NULL)
	{
		priority = atoi(c->args[1]);
		if(priority == 0 && strcmp(c->args[1],"0")){
			priority = 4;
			setCommand = 1;		
		}
		if(priority<-19)
		{
			priority = -19;
		}
		else if(priority>20)
		{
			priority = 20;
		}
	}
	else
	{
		printf("No arguments passed for nice command\n");
	}
	int childPID = fork();
	if(childPID == 0){
		which = PRIO_PROCESS;
		who = 0;	
		getpriority(which, who);
		setpriority(which, who, priority);
		int j = 0;
		int b = 0;		
		while(j<8)
		{
			if(setCommand != 1)
			{
				if(!strcmp(c->args[2],builtInCommands[j]))
				{
					b = 1;		
				}
			}
			else
			{
				if(!strcmp(c->args[1],builtInCommands[j]))
				{
					b = 1;		
				}
			}
			j++;
		}
		if(b){
			Cmd temp;
			temp = malloc(sizeof(struct cmd_t));
			temp->args = malloc(sizeof(char*));
			temp->in = Tnil;
			temp->out = Tnil;
			int i = 2;
			while(c->args[i] != NULL){
				temp->args[i-2] = malloc(strlen(c->args[i]));
				strcpy(temp->args[i-2],c->args[i]);
				i++;
			}
			builtInCmdExecutor(temp);			
			free(temp->args);
			free(temp);
			exit(0);			
		}	
		else{
			if(setCommand)
			{
				if(execvp(c->args[1], c->args+1) == -1){
					fprintf(stderr,"%s: command not found\n",c->args[1]);				
					exit(0);	
				}
			}
			else
			{
				if(execvp(c->args[2], c->args+2) == -1){
					fprintf(stderr,"%s: command not found\n",c->args[2]);				
					exit(0);	
				}
			}
		}
	}
	else{		
		waitpid(childPID,&status,0);
	}
}
Exemplo n.º 30
0
int main(int ac, char **av)
{
	int lc;				/* loop counter */
	char *msg;			/* message returned from parse_opts */
	int priority;
	int new_val = 2;	/* lower our priority from 0 to new_val */

	/* parse standard options */
	if ((msg = parse_opts(ac, av, (option_t *)NULL, NULL)) != (char *)NULL){
		tst_brkm(TBROK, tst_exit, "OPTION PARSING ERROR - %s", msg);
	}

	setup();			/* global setup */

	/* The following loop checks looping state if -i option given */

	for (lc = 0; TEST_LOOPING(lc); lc++) {
		/* reset Tst_count in case we are looping */
		Tst_count = 0;

		/*
		 * Lower the priority of this process from a default of 0
		 * to a new value of 2.  Then read the value using getpriority()
		 * to verify the change.
		 */
	
		/*
		 * We need to be careful here. We could possibly set our
		 * priority lower using PRIO_USER and then have no way
		 * to set it back.  So, let's use PRIO_PROCESS and make
		 * sure we affect this test only.
		 */
	
		/* call the system call with the TEST() macro */
		TEST(setpriority(PRIO_PROCESS, 0, new_val));
	
		if (TEST_RETURN != 0) {
			tst_resm(TFAIL, "call failed - errno = %d - "
				 "%s", TEST_ERRNO, strerror(TEST_ERRNO));
			continue;
		}
	
		if (STD_FUNCTIONAL_TEST) {
			/* get the priority that we just set */
			priority = getpriority(PRIO_PROCESS, 0);
	
			if (errno == -1) {
				tst_brkm(TBROK, cleanup, "getpriority call "
					 "failed - errno = %d - %s", errno,
					 strerror(errno));
			}
	
			if (priority == new_val) {
				tst_resm(TPASS, "functionality is correct");
			} else {
				tst_resm(TFAIL, "current priority (%d) and new "
					 "priority (%d) do not match",
					 priority, new_val);
			}
		} else {
			tst_resm(TPASS, "call succeeded");
		}
	}

	cleanup();

	/*NOTREACHED*/

  return(0);

}