Ejemplo n.º 1
0
void ferry_loop()
{
	/*
	Start, check if the south flag is checked, if so
	we want to skip doing north and just go straight to south.
	Once we get to south we want to check if the flag was set
	and if so we want to redeposit passengers before we pick up again.

	The same goes for the second loop, we check to see if the north flag
	was checked, if so we want to skip the south and go straight back 
	to north and pick up the queen there. 

	If the flag is set and we return to a bank that we were travelling away
	from, we want to re-deposit the passengers currently on the ferry back
	onto the shore, then reload them in the correct order (queen first)
	*/

	if(queen_south_flag!=1)
	{
		if(queen_north_flag==1)
		{
			queen_north_flag=0;
			//redeposit passengers
			redeposit_north();
		}
		arrive_north();
		//Set bank to transit
		curr_ferry.curr_bank = 2;
		print_proc();
		travel();
		//We reset the south flag as to not deposit passengers that wanted
		//To go to south in the first place, then they get mixed up with north
		//Passengers and go back to where they came from
		queen_south_flag=0;
	}

	//if north has queen waiting skip south and go north
	if(queen_north_flag!=1)
	{
		//if south has queen we are already here so just reset flag
		if(queen_south_flag==1)
		{
			queen_south_flag=0;
			//reposit passengers
			redeposit_south();
		}
		arrive_south();
		//Set bank to transit
		curr_ferry.curr_bank = 2;
		print_proc();
		travel();
		queen_north_flag=0;
	}
}
static void print_proc_depends(struct proc *pp, const int level)
{
	struct proc *depproc = NULL;
	endpoint_t dep;
#define COL { int i; for(i = 0; i < level; i++) printf("> "); }

	if(level >= NR_PROCS) {
		printf("loop??\n");
		return;
	}

	COL

	print_proc(pp);

	COL
	proc_stacktrace(pp);


	dep = P_BLOCKEDON(pp);
	if(dep != NONE && dep != ANY) {
		int procno;
		if(isokendpt(dep, &procno)) {
			depproc = proc_addr(procno);
			if(isemptyp(depproc))
				depproc = NULL;
		}
		if (depproc)
			print_proc_depends(depproc, level+1);
	}
}
Ejemplo n.º 3
0
void netstats(void) {
	if (getuid() == 0)
		firemon_drop_privs();
	
	pid_read(0);	// include all processes
	
	printf("Displaying network statistics only for sandboxes using a new network namespace.\n");
	
	// print processes
	while (1) {
		// set pid table
		int i;
		int itv = 5; 	// 5 second  interval
		pid_read(0);	// todo: preserve the last calculation if any, so we don't have to do get_stats()

		// start rx/tx measurements
		for (i = 0; i < MAX_PIDS; i++) {
			if (pids[i].level == 1)
				get_stats(i);
		}
		
		// wait 5 seconds
		firemon_sleep(itv);
		
		// grab screen size
		struct winsize sz;
		int row = 24;
		int col = 80;
		if (!ioctl(0, TIOCGWINSZ, &sz)) {
			col = sz.ws_col;
			row = sz.ws_row;
		}
		
		// start printing
		firemon_clrscr();
		char *header = get_header();
		if (strlen(header) > col)
			header[col] = '\0';
		printf("%s\n", header);
		if (row > 0)
			row--;
		free(header);

		// start rx/tx measurements
		for (i = 0; i < MAX_PIDS; i++) {
			if (pids[i].level == 1) {
				get_stats(i);
				print_proc(i, itv, col);
			}
		}
	}
}
Ejemplo n.º 4
0
void netstats(void) {
	pid_read(0);	// include all processes
	
	printf("Displaying network statistics only for sandboxes using a new network namespace.\n");
	
	// print processes
	while (1) {
		// set pid table
		int i;
		int itv = 5; 	// 5 second  interval
		pid_read(0);

		// start rx/tx measurements
		for (i = 0; i < max_pids; i++) {
			if (pids[i].level == 1)
				get_stats(i);
		}
		
		// wait 5 seconds
		firemon_sleep(itv);
		
		// grab screen size
		struct winsize sz;
		int row = 24;
		int col = 80;
		if (!ioctl(0, TIOCGWINSZ, &sz)) {
			col = sz.ws_col;
			row = sz.ws_row;
		}
		
		// start printing
		firemon_clrscr();
		char *header = get_header();
		if (strlen(header) > (size_t)col)
			header[col] = '\0';
		printf("%s\n", header);
		if (row > 0)
			row--;
		free(header);

		// start rx/tx measurements
		for (i = 0; i < max_pids; i++) {
			if (pids[i].level == 1) {
				get_stats(i);
				print_proc(i, itv, col);
			}
		}
#ifdef HAVE_GCOV
			__gcov_flush();
#endif
	}
}
Ejemplo n.º 5
0
PRIVATE void ser_dump_proc_cpu(void)
{
	struct proc *pp;
	unsigned cpu;

	for (cpu = 0; cpu < ncpus; cpu++) {
		printf("CPU %d processes : \n", cpu);
		for (pp= BEG_USER_ADDR; pp < END_PROC_ADDR; pp++) {
			if (isemptyp(pp) || pp->p_cpu != cpu)
				continue;
			print_proc(pp);
		}
	}
}
/* 
    Print all procs
*/
void print_procs(Procs procs) {
    Proc first = procs->first;
    Procs rest = procs->rest;
    
    // Print all procs
    if (first) {
        print_proc(first);
        printf("\n");

    }
    if (rest) {
        print_procs(rest);
    }
}
Ejemplo n.º 7
0
void arch_proc_setcontext(struct proc *p, struct stackframe_s *state,
	int isuser, int trap_style)
{
	if(isuser) {
		/* Restore user bits of psw from sc, maintain system bits
		 * from proc.
		 */
		state->psw  =  (state->psw & X86_FLAGS_USER) |
			(p->p_reg.psw & ~X86_FLAGS_USER);
	}

	/* someone wants to totally re-initialize process state */
	assert(sizeof(p->p_reg) == sizeof(*state));
	memcpy(&p->p_reg, state, sizeof(*state));

	/* further code is instructed to not touch the context
	 * any more
	 */
	p->p_misc_flags |= MF_CONTEXT_SET;

	/* on x86 this requires returning using iret (KTS_INT)
	 * so that the full context is restored instead of relying on
	 * the userspace doing it (as it would do on SYSEXIT).
	 * as ESP and EIP are also reset, userspace won't try to
	 * restore bogus context after returning.
	 *
	 * if the process is not blocked, or the kernel will ignore
	 * our trap style, we needn't panic but things will probably
	 * not go well for the process (restored context will be ignored)
	 * and the situation should be debugged.
	 */
	if(!(p->p_rts_flags)) {
		printf("WARNINIG: setting full context of runnable process\n");
		print_proc(p);
		util_stacktrace();
	}
	if(p->p_seg.p_kern_trap_style == KTS_NONE)
		printf("WARNINIG: setting full context of out-of-kernel process\n");
	p->p_seg.p_kern_trap_style = trap_style;
}
Ejemplo n.º 8
0
void procd_ps2(void) {
  proc_p p;
  int i;
  pgrp_p pg;
  session_p s;
  fprintf(stderr,"proc_table: %p, envid: %d\n",proc_table,proc_table->procd_envid);

  for (i = 0; i < MAXPROC; i++) {
    fprintf(stderr,"%d ",(bit_test(proc_table->procs_used,i)) ?1:0);
    p = &proc_table->procs[i];
    print_proc(p);
  }
  for (i = 0; i < MAXPGRP; i++) {
    fprintf(stderr,"%d ",(bit_test(proc_table->pgrps_used,i)) ?1:0);
    pg = &proc_table->pgrps[i];
    print_pgrp(pg);
  }
  for (i = 0; i < MAXSESSION; i++) {
    fprintf(stderr,"%d ",(bit_test(proc_table->sessions_used,i)) ?1:0);
    s = &proc_table->sessions[i];
    print_session(s);
  }
  fprintf(stderr,"done\n");
}
Ejemplo n.º 9
0
void print_procs(int maxlines,
	struct proc *proc1, struct proc *proc2,
	struct mproc *mproc)
{
	int p, nprocs, tot=0;
	u64_t idleticks = cvu64(0);
	u64_t kernelticks = cvu64(0);
	u64_t systemticks = cvu64(0);
	u64_t userticks = cvu64(0);
	u64_t total_ticks = cvu64(0);
	unsigned long tcyc;
	unsigned long tmp;
	int blockedseen = 0;
	struct tp tick_procs[PROCS];

	for(p = nprocs = 0; p < PROCS; p++) {
		if(isemptyp(&proc2[p]))
			continue;
		tick_procs[nprocs].p = proc2 + p;
		if(proc1[p].p_endpoint == proc2[p].p_endpoint) {
			tick_procs[nprocs].ticks =
				sub64(proc2[p].p_cycles, proc1[p].p_cycles);
		} else {
			tick_procs[nprocs].ticks =
				proc2[p].p_cycles;
		}
		total_ticks = add64(total_ticks, tick_procs[nprocs].ticks);
		if(p-NR_TASKS == IDLE) {
			idleticks = tick_procs[nprocs].ticks;
			continue;
		}
		if(p-NR_TASKS == KERNEL) {
			kernelticks = tick_procs[nprocs].ticks;
			continue;
		}
		if(mproc[proc2[p].p_nr].mp_procgrp == 0)
			systemticks = add64(systemticks, tick_procs[nprocs].ticks);
		else if (p > NR_TASKS)
			userticks = add64(userticks, tick_procs[nprocs].ticks);

		nprocs++;
	}

	if (!cmp64u(total_ticks, 0))
		return;

	qsort(tick_procs, nprocs, sizeof(tick_procs[0]), cmp_ticks);

	tcyc = div64u(total_ticks, SCALE);

	tmp = div64u(userticks, SCALE);
	printf("CPU states: %6.2f%% user, ", 100.0*(tmp)/tcyc);

	tmp = div64u(systemticks, SCALE);
	printf("%6.2f%% system, ", 100.0*tmp/tcyc);

	tmp = div64u(kernelticks, SCALE);
	printf("%6.2f%% kernel, ", 100.0*tmp/tcyc);

	tmp = div64u(idleticks, SCALE);
	printf("%6.2f%% idle", 100.0*tmp/tcyc);

#define NEWLINE do { printf("\n"); if(--maxlines <= 0) { return; } } while(0) 
	NEWLINE;
	NEWLINE;

	printf("  PID USERNAME PRI NICE   SIZE STATE   TIME     CPU COMMAND");
	NEWLINE;
	for(p = 0; p < nprocs; p++) {
		struct proc *pr;
		int pnr;
		int level = 0;

		pnr = tick_procs[p].p->p_nr;

		if(pnr < 0) {
			/* skip old kernel tasks as they don't run anymore */
			continue;
		}

		pr = tick_procs[p].p;

		/* If we're in blocked verbose mode, indicate start of
		 * blocked processes.
		 */
		if(blockedverbose && pr->p_rts_flags && !blockedseen) {
			NEWLINE;
			printf("Blocked processes:");
			NEWLINE;
			blockedseen = 1;
		}

		print_proc(&tick_procs[p], &mproc[pnr], tcyc);
		NEWLINE;

		if(!blockedverbose)
			continue;

		/* Traverse dependency chain if blocked. */
		while(pr->p_rts_flags) {
			endpoint_t dep = NONE;
			struct tp *tpdep;
			level += 5;

			if((dep = P_BLOCKEDON(pr)) == NONE) {
				printf("not blocked on a process");
				NEWLINE;
				break;
			}

			if(dep == ANY)
				break;

			tpdep = lookup(dep, tick_procs, nprocs);
			pr = tpdep->p;
			printf("%*s> ", level, "");
			print_proc(tpdep, &mproc[pr->p_nr], tcyc);
			NEWLINE;
		}
	}
}
Ejemplo n.º 10
0
static void print_procs(int maxlines,
	struct proc *proc1, struct proc *proc2, int cputimemode)
{
	int p, nprocs;
	u64_t idleticks = 0;
	u64_t kernelticks = 0;
	u64_t systemticks = 0;
	u64_t userticks = 0;
	u64_t total_ticks = 0;
	int blockedseen = 0;
	static struct tp *tick_procs = NULL;

	if (tick_procs == NULL) {
		tick_procs = malloc(nr_total * sizeof(tick_procs[0]));

		if (tick_procs == NULL) {
			fprintf(stderr, "Out of memory!\n");
			exit(1);
		}
	}

	for(p = nprocs = 0; p < nr_total; p++) {
		u64_t uticks;
		if(!(proc2[p].p_flags & USED))
			continue;
		tick_procs[nprocs].p = proc2 + p;
		tick_procs[nprocs].ticks = cputicks(&proc1[p], &proc2[p], cputimemode);
		uticks = cputicks(&proc1[p], &proc2[p], 1);
		total_ticks = total_ticks + uticks;
		if(p-NR_TASKS == IDLE) {
			idleticks = uticks;
			continue;
		}
		if(p-NR_TASKS == KERNEL) {
			kernelticks = uticks;
		}
		if(!(proc2[p].p_flags & IS_TASK)) {
			if(proc2[p].p_flags & IS_SYSTEM)
				systemticks = systemticks + tick_procs[nprocs].ticks;
			else
				userticks = userticks + tick_procs[nprocs].ticks;
		}

		nprocs++;
	}

	if (total_ticks == 0)
		return;

	qsort(tick_procs, nprocs, sizeof(tick_procs[0]), cmp_procs);

	printf("CPU states: %6.2f%% user, ", 100.0 * userticks / total_ticks);
	printf("%6.2f%% system, ", 100.0 * systemticks / total_ticks);
	printf("%6.2f%% kernel, ", 100.0 * kernelticks/ total_ticks);
	printf("%6.2f%% idle", 100.0 * idleticks / total_ticks);

#define NEWLINE do { printf("\n"); if(--maxlines <= 0) { return; } } while(0)
	NEWLINE;

	printf("CPU time displayed ('%c' to cycle): %s; ",
		TIMECYCLEKEY, cputimemodename(cputimemode));
	printf(" sort order ('%c' to cycle): %s", ORDERKEY, ordername(order));
	NEWLINE;

	NEWLINE;

	printf("  PID USERNAME PRI NICE    SIZE STATE   TIME     CPU COMMAND");
	NEWLINE;
	for(p = 0; p < nprocs; p++) {
		struct proc *pr;
		int level = 0;

		pr = tick_procs[p].p;

		if((pr->p_flags & IS_TASK) && pr->p_pid != KERNEL) {
			/* skip old kernel tasks as they don't run anymore */
			continue;
		}

		/* If we're in blocked verbose mode, indicate start of
		 * blocked processes.
		 */
		if(blockedverbose && (pr->p_flags & BLOCKED) && !blockedseen) {
			NEWLINE;
			printf("Blocked processes:");
			NEWLINE;
			blockedseen = 1;
		}

		print_proc(&tick_procs[p], total_ticks);
		NEWLINE;

		if(!blockedverbose)
			continue;

		/* Traverse dependency chain if blocked. */
		while(pr->p_flags & BLOCKED) {
			endpoint_t dep = NONE;
			struct tp *tpdep;
			level += 5;

			if((dep = pr->p_blocked) == NONE) {
				printf("not blocked on a process");
				NEWLINE;
				break;
			}

			if(dep == ANY)
				break;

			tpdep = lookup(dep, tick_procs, nprocs);
			pr = tpdep->p;
			printf("%*s> ", level, "");
			print_proc(tpdep, total_ticks);
			NEWLINE;
		}
	}
}
Ejemplo n.º 11
0
void arrive_south()
{
	//lock
	mutex_lock_interruptible(&lock);
	printk("%s: **Locked**\n", __FUNCTION__);
	
	//arrive at south_bank
	printk("%s: Arrived at south bank\n", __FUNCTION__);
	curr_ferry.curr_bank = 1;

	print_proc();

	release_passengers();

	printk("%s: Passengers released, unlocking and waiting\n", __FUNCTION__);
	//release lock
	mutex_unlock(&lock);
	//Wait 2 seconds for any extra passengers
	msleep(2000);
	//Lock again and begin loading passengers
	mutex_lock_interruptible(&lock);
	printk("%s: Waiting over, locked and loading passengers\n", __FUNCTION__);

	//load passengers
	if(south_bank.queen == 1)
	{
		printk("%s: Picking up south queen\n", __FUNCTION__);
		curr_ferry.queen++;
		south_bank.queen--;
		curr_ferry.compartments+=5;
		curr_ferry_passengers++;
		total_ferried++;
	}
	if(south_bank.nobles > 0)
	{
		printk("%s: Picking up south nobles: %d\n", __FUNCTION__, south_bank.nobles);
		while((curr_ferry.compartments + 3) <= 15 && south_bank.nobles > 0)
		{
			curr_ferry.nobles++;
			south_bank.nobles--;
			curr_ferry.compartments+=3;
			curr_ferry_passengers++;
			total_ferried++;
		}
	}
	if(south_bank.peasants > 0)
	{
		printk("%s: Picking up south peasants: %d\n", __FUNCTION__, south_bank.peasants);
		while(curr_ferry.compartments < 15 && south_bank.peasants > 0)
		{
			curr_ferry.peasants++;
			south_bank.peasants--;
			curr_ferry.compartments++;
			curr_ferry_passengers++;
			total_ferried++;
		}
	}
	//release lock
	mutex_unlock(&lock);
	printk("%s: **Unlocked**\n", __FUNCTION__);
}
Ejemplo n.º 12
0
int main (void)
{
	int i, c;

	initscr ();
	noecho ();
	curs_set (0);

	if (has_colors () == FALSE)
	{
		fprintf (stderr, "Your terminal doesn't support colors.\n");
		global.colors = 0;
	}
	else
	{
		global.colors = 1;
		start_color ();

		if (use_default_colors () == OK)
			bg = -1;

		color (GREEN, COLOR_GREEN);
		color (YELLOW, COLOR_YELLOW);
		color (RED, COLOR_RED);
		color (CYAN, COLOR_CYAN);
	}


	signal (SIGINT, &handler);
	signal (SIGTERM, &handler);
	signal (SIGSEGV, &handler);

	global.loadavg.file = fopen ("/proc/loadavg", "r");
	global.cpu = fopen ("/proc/stat", "r");
	global.mtab = fopen ("/etc/mtab", "r");
	global.net = fopen ("/proc/net/dev", "r");
	global.wireless = fopen ("/proc/net/wireless", "r");

	/* Init global.battery */
	global.battery.ok = 1;
	strncpy (global.battery.dir.location, "/proc/acpi/battery/", 128);
	global.battery.dir.dir = opendir (global.battery.dir.location);

	if (global.battery.dir.dir != NULL)
	{
		while (1)
		{
			global.battery.dir.content = readdir (global.battery.dir.dir);

			if (!strcmp (global.battery.dir.content->d_name, "."))
				break;
			else if (!strcmp (global.battery.dir.content->d_name, ".."))
				break;
		}

		closedir (global.battery.dir.dir);

		if (global.battery.dir.content != NULL)
		{
			strcat (global.battery.dir.location, global.battery.dir.content->d_name);
			snprintf (global.battery.state.location, 128, "%s/state", global.battery.dir.location);
			snprintf (global.battery.info.location, 128, "%s/info", global.battery.dir.location);

			global.battery.state.file = fopen (global.battery.state.location, "r");
			global.battery.info.file = fopen (global.battery.info.location, "r");

			if (global.battery.state.file == NULL
				|| global.battery.info.file == NULL)
			{
				fprintf (stderr, "Can't open %s/state or %s/info while %s is present, check your ACPI configuration or remove the directory %s.\n",
						global.battery.dir.location, global.battery.dir.location,
						global.battery.dir.location, global.battery.dir.location);

				global.battery.ok = 0;
			}
		}
		else
		{
			fprintf (stderr, "Nothing in /proc/acpi/battery or can't list directory while directory present.\n");
			global.battery.ok = 0;
		}
	}
	else
	{
		fprintf (stderr, "No /proc/acpi/battery directory, skipping the battery part.\n");
		global.battery.ok = 0;
	}

	/* Get static system informations */
	global.nprocs = get_nprocs ();
	uname (&global.uname);

	{ /* get processor */
		FILE *f = fopen ("/proc/cpuinfo", "r");
		char buf[256];

		strncpy (global.processor, global.uname.machine, 256);

		if (f != NULL)
		{
			while (fgets (buf, sizeof buf, f))
			{
				if (!strncmp (buf, "model name", 10))
				{
					char *p = strchr (buf, ':');
					strncpy (global.processor, &p[2], 256);
					p = strchr (global.processor, '\n'); *p = 0;
					break;
				}
			}

			fclose (f);
		}

		global.processor[255] = 0;
	}

	if (global.cpu != NULL)
	{
		extern struct cpu_t *ocpu, *ncpu;

		ocpu = malloc (global.nprocs * sizeof (struct cpu_t));
		ncpu = malloc (global.nprocs * sizeof (struct cpu_t));

		if (ocpu == NULL || ncpu == NULL)
			fclose (global.cpu), global.cpu = NULL;
	}

	halfdelay (1);
	while ((c = getch ()) != '\n')
	{
		global.line = 0;

		switch (c)
		{
			case 'r': clear (); break;
		}

		/* Check system informations */
		if (0 != sysinfo (&global.sys))
			continue;

		/* Print informations */
		for (i = 0; show_fields[i] != EndOfFields; ++i)
		{
			if (show_fields[i] == Uname)
			{
				mvprintw (global.line++, 0, "%s %s\n%s\n", global.uname.nodename, global.uname.release, global.processor);
				global.line++;
			}

			if (global.loadavg.file != NULL && show_fields[i] == Loadavg)
			{
				char tmp[256];

				loadavg ();
				snprintf (tmp, 256, "Load average: 1min: $4%.2f$0 / 5min: $4%.2f$0 / 15min: $4%.2f$0\n",
						global.loadavg.loads[0],
						global.loadavg.loads[1],
						global.loadavg.loads[2]);
				print_color (global.line++, 0, tmp);
			
				snprintf (tmp, 256, "Tasks: $4%d$0 running, $4%d$0 total, last PID used : $4%d$0\n",
						global.loadavg.prun, global.loadavg.ptotal, global.loadavg.pid);
				print_color (global.line++, 0, tmp);
			}
	
			refresh ();
	
			if (show_fields[i] == Date) /* Date */
			{
				time_t timestamp= time (NULL);
				struct tm *t = localtime (&timestamp);
	
				mvprintw (global.line, 0, "Time: %02d:%02d:%02d |",
						t->tm_hour,
						t->tm_min,
						t->tm_sec);
				refresh ();
			}
	
			if (show_fields[i] == Date) /* Uptime */
			{
				int uptime = global.sys.uptime;
				int up, day, hour, min, sec;
	
				day = uptime / 86400;
				up = uptime - (day * 86400);
				hour = up / 3600;
				up -= hour * 3600;
				min = up / 60;
				sec = up - min * 60;
	
				mvprintw (global.line++, 17, "Uptime: %d day%s, %02d:%02d:%02d\n",
						day, (day > 1 ? "s" : ""),
						hour, min, sec);
				refresh ();
			}
	
			if (global.cpu != NULL && show_fields[i] == Cpu)
			{
				int i;
				for (i = 0; i < global.nprocs; ++i)
					cpubar (i);
			}
	
			if (show_fields[i] == Ram)  rambar ();
			if (show_fields[i] == Swap) swapbar ();
	
			if (global.mtab != NULL && show_fields[i] == Disk)
				diskbar ();
	
			if (global.wireless != NULL && show_fields[i] == Wireless)
				wirelessbar ();
	
			if (global.net != NULL && show_fields[i] == Network)
				netbar ();
	
			if (global.battery.ok && show_fields[i] == Battery)
				batterybar ();
	
			if (show_fields[i] == Process) print_proc ();
		}

		sleep (1);
	}

	raise (SIGTERM);

	return 0;
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{
	arg_parse(argc, argv);

	page_shift = __getpageshift();

#if 0
	choose_dimensions();
#endif
	if (!old_h_option) {
		const char *head;
		switch (ps_format) {
		default:	/* can't happen */
		case 0:
			head = "  PID TTY         TIME CMD";
			break;
		case 'l':
			head =
			    "  F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN    TTY       TIME CMD";
			break;
		case 'f':
			head =
			    "  UID   PID  PPID  C STIME   TTY       TIME CMD";
			break;
		case 'j':
			head = "  PID  PGID   SID TTY         TIME CMD";
			break;
		case 'u' | 0x80:
			head =
			    "  UID   PID %CPU %MEM   VSZ   RSS   TTY   S START     TIME COMMAND";
			break;
		case 'v' | 0x80:
			head =
			    "  PID   TTY   S     TIME  MAJFL TRS DRS   RSS %MEM COMMAND";
			break;
		case 'j' | 0x80:
			head =
			    " PPID   PID  PGID   SID   TTY   TPGID S   UID     TIME COMMAND";
			break;
		case 'l' | 0x80:
			head =
			    "  F   UID   PID  PPID PRI  NI   VSZ  RSS WCHAN  S   TTY       TIME COMMAND";
			break;
		}
		printf("%s\n", head);
	}
	if (want_one_pid) {
		if (stat2proc(want_one_pid))
			print_proc();
		else
			exit(1);
	} else {
		struct dirent *ent;	/* dirent handle */
		DIR *dir;
		int ouruid;
		int found_a_proc;
		found_a_proc = 0;
		ouruid = getuid();
		dir = opendir("/proc");
		if (!dir)
			exit(1);
		while ((ent = readdir(dir))) {
			if (*ent->d_name < '0' || *ent->d_name > '9')
				continue;
			if (!stat2proc(atoi(ent->d_name)))
				continue;
			if (want_one_command) {
				if (strcmp(want_one_command, P_cmd))
					continue;
			} else {
				if (!select_notty && P_tty == -1)
					continue;
				if (!select_all && P_euid != ouruid)
					continue;
			}
			found_a_proc++;
			print_proc();
		}
		closedir(dir);
		exit(!found_a_proc);
	}
	return 0;
}
Ejemplo n.º 14
0
int main(){
  queue *test = malloc(sizeof(queue)); test->head = NULL; test->tail = NULL;
  queue *priority = malloc(sizeof(queue)); priority->head = NULL; priority->tail = NULL;
  queue *secondary = malloc(sizeof(queue)); secondary->head = NULL; secondary->tail = NULL;
  //  node_t *priority = NULL; //queue 1
  //  node_t *secondary = NULL; //queue 2

  /*
  //start temp
  proc *p1 = (proc *)malloc(sizeof(proc));
  strcpy(p1->name,"p1");
  p1->priority = 0;
  p1->pid = 33;
  p1->runtime = 5;
  push(&test,*p1);
  
  proc *p2 = (proc *)malloc(sizeof(proc));
  strcpy(p2->name,"p2");
  p2->priority = 0;
  p2->pid = 33;
  p2->runtime = 5;
  push(&test,*p2);
  
  proc popped = pop(&test);
  //  print_proc(&popped);
  push(&test,popped);
  print_list(test);
  //  pop(&test);
  //end temp
  */
  
  readFile(&priority,0);//loads all processes with priority == 0
  readFile(&secondary,1);//loads all processes with priority != 0
  print_list(priority);
  puts("----");
  //print_list(secondary);
  //create an array of available memory
  int avail_mem[TOTAL_MEMORY] = {0};

  //iterate through all priority processes
  node_t *temp = priority->head;
  while (temp != NULL){
    pid_t pid = fork();
    if (pid == 0){
      //child process
      puts("child:");
      execlp("./process",NULL);
      exit(0);
    }else if (pid >0){
      //parent process
      temp->val.pid = pid; //set the pid of the process
      //allocate the required memory
      int i = 0;
      temp->val.address = i;
      for (i = 0; i < temp->val.memory; i++){
	avail_mem[i] = 1;
      }
      printf("[parent] Executing process: %s, priority: %d, pid: %d, memory: %d, runtime: %d\n",
	     temp->val.name,temp->val.priority,temp->val.pid,temp->val.memory, temp->val.runtime);
      printf("[parent] waiting %d seconds...:\n",temp->val.runtime);
      sleep(temp->val.runtime); //sleep for the needed runtime
      puts("[parent] Sending SIGINT...");
      kill(pid,SIGINT);
      waitpid(pid,0,0);
      //free the allocated memory
      printf("[parent] Current available memory: %dMB\n",freeMemoryAmount(avail_mem,TOTAL_MEMORY));
      printf("[parent] Freeing: %dMB of memory\n",temp->val.memory);
      for (int j = 0; j < temp->val.memory; j++){
	avail_mem[j] = 0;
      }
      //print process to be deleted
      printf("[parent] Deleting process: %s, priority: %d, pid: %d, runtime: %d\n",
	     temp->val.name,temp->val.priority,temp->val.pid,temp->val.runtime);
      //delete process from queue
      temp = temp->next;
      pop(&priority);
      puts("--------------------------------------------");
    }else{
      //fork failed
    }
  }
  
  //iterate through all the secondary processes
  print_list(secondary);
  puts("--------------------------------------------");
  int memory_index = 0;
  temp = secondary->head;
  while(temp != NULL){//while items in queue
    proc popped_proc = pop(&secondary);//pop the next process
    
    //check if new process and available memory
    if (popped_proc.suspended == 0 && popped_proc.memory <= freeMemoryAmount(avail_mem,TOTAL_MEMORY)){
      //create a new process
      pid_t pid = fork();
      if (pid == 0){
	//child
	execlp("./process",NULL);
	exit(0);
      }else if(pid > 0){
	//parent
	printf("Creating new process: ");print_proc(&popped_proc);

	//allocate the needed memory
	printf("ALLOCATING memory from: %d, to %d\n",memory_index,memory_index + popped_proc.memory -1); //temp
	popped_proc.address = memory_index;
	for (int i = 0; i < popped_proc.memory; i++){
	  avail_mem[memory_index+i] = 1;
	}
	memory_index += popped_proc.memory;
	printf("MEMORY_INDEX: %d\n",memory_index);

	print_memory(avail_mem,TOTAL_MEMORY);//temp
	
	//new process to be created
	sleep(1);
	kill(pid,SIGTSTP);
	popped_proc.pid = pid; //set the process id [TODO: FIX PID]
	popped_proc.runtime -= 1; //decrement the runtime
	popped_proc.suspended = 1; //update the suspended boolean
	//add the process back on the queue
	push(&secondary, popped_proc);
      }else{
	perror("Error forking\n");
      }
    }else if(popped_proc.suspended == 1 && popped_proc.runtime != 1){
      //must continue process
      printf("Resuming process: ");print_proc(&popped_proc);
      kill(popped_proc.pid,SIGCONT);
      sleep(1); //sleep for once second
      kill(popped_proc.pid,SIGTSTP);
      popped_proc.runtime -= 1;
      //add the process back on the queue
      push(&secondary, popped_proc);
    }else if (popped_proc.runtime == 1){
      //only 1 second left on process
      printf("One second left on Process: ");print_proc(&popped_proc);
      //run for the remaining second

      //delocate the memory taken
      printf("DEALLOCATING memory from %d, to %d\n",memory_index - 1, memory_index - popped_proc.memory);
      for (int i = 1; i <= popped_proc.memory; i++){
	avail_mem[memory_index - i] = 0;
      }      
      memory_index -= popped_proc.memory;
      printf("MEMORY_INDEX: %d\n",memory_index);

      print_memory(avail_mem,TOTAL_MEMORY);//temp

      //run the process
      kill(popped_proc.pid,SIGCONT);
      sleep(1); //sleep for once second
      kill(popped_proc.pid,SIGINT);
      waitpid(popped_proc.pid,0,0);
    }else {
      //not enough memory, push back on the queue
      printf("Not enough memory for: ");print_proc(&popped_proc);
      push(&secondary, popped_proc);
    }   
    temp = secondary->head;//go to next node
  }
  puts("---------------COMPLETE--------------------");
  return 0;
}