Пример #1
0
static int
lynx_create_inferior (char *program, char **allargs)
{
  struct process_info *new_process;
  int pid;

  lynx_debug ("lynx_create_inferior ()");

  pid = fork ();
  if (pid < 0)
    perror_with_name ("fork");

  if (pid == 0)
    {
      int pgrp;

      /* Switch child to its own process group so that signals won't
         directly affect gdbserver. */
      pgrp = getpid();
      setpgid (0, pgrp);
      ioctl (0, TIOCSPGRP, &pgrp);
      lynx_ptrace (PTRACE_TRACEME, null_ptid, 0, 0, 0);
      execv (program, allargs);
      fprintf (stderr, "Cannot exec %s: %s.\n", program, strerror (errno));
      fflush (stderr);
      _exit (0177);
    }

  new_process = add_process (pid, 0);
  /* Do not add the process thread just yet, as we do not know its tid.
     We will add it later, during the wait for the STOP event corresponding
     to the lynx_ptrace (PTRACE_TRACEME) call above.  */
  return pid;
}
Пример #2
0
static int
fbsd_create_inferior (char *program, char **allargs)
{
  void *new_process;
  int pid;

  pid = vfork ();
  if (pid < 0)
    perror_with_name ("vfork");

  if (pid == 0)
    {
      ptrace (PT_TRACE_ME, 0, 0, 0);

      setpgid (0, 0);

      execv (program, allargs);

      fprintf (stderr, "Cannot exec %s: %s.\n", program,
	       strerror (errno));
      fflush (stderr);
      _exit (0177);
    }

  new_process = add_process (pid);
  add_thread (pid, new_process);

  return pid;
}
Пример #3
0
void
fbsd_attach_lwp (int pid, int tid)
{
  struct process_info *new_process;

  if (ptrace (PT_ATTACH, pid, 0, 0) != 0)
    {
      fprintf (stderr, "Cannot attach to process %d: %s (%d)\n", pid,
	       strerror (errno), errno);
      fflush (stderr);

      /* If we fail to attach to an LWP, just return.  */
      if (!using_threads)
	_exit (0177);
      return;
    }

  new_process = (struct process_info *) add_process (pid);
  add_thread (tid, new_process);

  /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
     brings it to a halt.  We should ignore that SIGSTOP and resume the process
     (unless this is the first process, in which case the flag will be cleared
     in fbsd_attach).

     On the other hand, if we are currently trying to stop all threads, we
     should treat the new thread as if we had sent it a SIGSTOP.  This works
     because we are guaranteed that add_process added us to the end of the
     list, and so the new thread has not yet reached wait_for_sigstop (but
     will).  */
  if (! stopping_threads)
    new_process->stop_expected = 1;
}
Пример #4
0
static void do_listen(char *port)
{
	struct addrinfo hints;
	struct addrinfo *result, *rp;
	int sfd, s, cfd;
	struct sockaddr_storage peer_addr;
	socklen_t peer_addr_len;
	int pid;

	if (!debug)
		signal_setup(SIGCHLD, clean_up);

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	s = getaddrinfo(NULL, port, &hints, &result);
	if (s != 0)
		pdie("getaddrinfo: error opening %s", port);

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sfd = socket(rp->ai_family, rp->ai_socktype,
			     rp->ai_protocol);
		if (sfd < 0)
			continue;

		if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
			break;

		close(sfd);
	}

	if (rp == NULL)
		pdie("Could not bind");

	freeaddrinfo(result);

	if (listen(sfd, backlog) < 0)
		pdie("listen");

	peer_addr_len = sizeof(peer_addr);

	do {
		cfd = accept(sfd, (struct sockaddr *)&peer_addr, &peer_addr_len);
		printf("connected!\n");
		if (cfd < 0 && errno == EINTR)
			continue;
		if (cfd < 0)
			pdie("connecting");

		pid = do_connection(cfd, &peer_addr, peer_addr_len);
		if (pid > 0)
			add_process(pid);

	} while (!done);

	kill_clients();
}
Пример #5
0
static void
handle_clone(Event * event) {
	Process *p;

	debug(DEBUG_FUNCTION, "handle_clone(pid=%d)", event->proc->pid);

	p = malloc(sizeof(Process));
	if (!p) {
		perror("malloc()");
		exit(1);
	}
	memcpy(p, event->proc, sizeof(Process));
	p->pid = event->e_un.newpid;
	p->parent = event->proc;

	/* We save register values to the arch pointer, and these need
	   to be per-thread.  */
	p->arch_ptr = NULL;

	if (pending_new(p->pid)) {
		pending_new_remove(p->pid);
		if (p->event_handler != NULL)
			destroy_event_handler(p);
		if (event->proc->state == STATE_ATTACHED && options.follow) {
			p->state = STATE_ATTACHED;
		} else {
			p->state = STATE_IGNORED;
		}
		continue_process(p->pid);
		add_process(p);
	} else {
		p->state = STATE_BEING_CREATED;
		add_process(p);
	}

	if (p->leader == p)
		clone_breakpoints(p, event->proc->leader);
	else
		/* Thread groups share breakpoints.  */
		p->breakpoints = NULL;

	if (event->type == EVENT_VFORK)
		continue_after_vfork(p);
	else
		continue_process(event->proc->pid);
}
Пример #6
0
static pid_t
do_attach (pid_t pid)
{
  procfs_status status;
  struct sigevent event;

  if (nto_inferior.ctl_fd != -1)
    {
      close (nto_inferior.ctl_fd);
      init_nto_inferior (&nto_inferior);
    }
  xsnprintf (nto_inferior.nto_procfs_path, PATH_MAX - 1, "/proc/%d/as", pid);
  nto_inferior.ctl_fd = open (nto_inferior.nto_procfs_path, O_RDWR);
  if (nto_inferior.ctl_fd == -1)
    {
      TRACE ("Failed to open %s\n", nto_inferior.nto_procfs_path);
      init_nto_inferior (&nto_inferior);
      return -1;
    }
  if (devctl (nto_inferior.ctl_fd, DCMD_PROC_STOP, &status, sizeof (status), 0)
      != EOK)
    {
      do_detach ();
      return -1;
    }
  nto_inferior.pid = pid;
  /* Define a sigevent for process stopped notification.  */
  event.sigev_notify = SIGEV_SIGNAL_THREAD;
  event.sigev_signo = SIGUSR1;
  event.sigev_code = 0;
  event.sigev_value.sival_ptr = NULL;
  event.sigev_priority = -1;
  devctl (nto_inferior.ctl_fd, DCMD_PROC_EVENT, &event, sizeof (event), 0);

  if (devctl (nto_inferior.ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status),
	      0) == EOK
      && (status.flags & _DEBUG_FLAG_STOPPED))
    {
      ptid_t ptid;
      struct process_info *proc;

      kill (pid, SIGCONT);
      ptid = ptid_build (status.pid, status.tid, 0);
      the_low_target.arch_setup ();
      proc = add_process (status.pid, 1);
      proc->tdesc = nto_tdesc;
      TRACE ("Adding thread: pid=%d tid=%ld\n", status.pid,
	     ptid_get_lwp (ptid));
      nto_find_new_threads (&nto_inferior);
    }
  else
    {
      do_detach ();
      return -1;
    }

  return pid;
}
Пример #7
0
//Recursive function to add process to linked list.
void add_process(process *curr, process *p)
{	
	if (curr->next == NULL) {
		curr->next = p;
		p->prev = curr;
	}
	else
	{add_process(curr->next, p);}
}
Пример #8
0
void main( ){

	int opt= 0;
	int p;
	process *proc;
	list *l;

	l= (list * ) malloc (sizeof(list));


	make_list(l);
	printf("\n\n\n");
	printf("\tTrabalho ED1 - Marcos Oleiro - Listas Simplesmente Encadeadas\n");
	printf("\n\n\n");
	while (opt != 3) {

		printf("1 - Adcionar Processos.\n");
		printf("2 - Listar Processos.\n");
		printf("3 - Sair.\n\n\n");

		printf("Digite sua opcao: ");
		scanf ("%d", &opt);
		printf("\n");
		switch (opt) {

			case 1:
				// process *proc= NULL ;
				printf("\n");
				proc = newProcess();
				printf("\n\n");
				add_process(l,proc);
				printf("ID: %d, Prioridade: %d, Horario: %d:%d:%d\n",proc->id, proc->priority,
					proc->h->hour,proc->h->minute,proc->h->second);
				proc = NULL;
				printf("\n\n");



			break;

			case 2:
				// printf("Opção 2.\n");
				// sort_priority(l);
				sort_list(l);
				print_list(l);

			break;

			case 3:
				// printf("Opção 3.\n");

			break;

		}
	}
}
Пример #9
0
static struct process_info *
lynx_add_process (int pid, int attached)
{
  struct process_info *proc;

  proc = add_process (pid, attached);
  proc->tdesc = lynx_tdesc;
  proc->priv = xcalloc (1, sizeof (*proc->priv));
  proc->priv->last_wait_event_ptid = null_ptid;

  return proc;
}
Пример #10
0
void kmain(){
  cli("kmain()");

  clear_screen();
  kprintln("KERNEL STARTED");
    
  if(mb_magic != 0x2BADB002){
    /* Something went not according to specs. Print an error */
    /* message and halt, but do *not* rely on the multiboot */
    /* data structure. */
    kprint("ERROR: Invalid multiboot magic number: ");
    kprintln_uint32(mb_magic);
    return;
  }

  kutil_init();
  kprintln("kutil initialised");

  memory_init();
  kprintln("memory initialised");

  interrupts_init();
  add_interrupt_handler(0x80, (uint32_t) interrupt_handler);  
  kprintln("interrupts initialised");

  processes_init();
  kprintln("processes initialised");

  clear_screen();

  add_process(&print_A);
  add_process(&print_B);

  //check_process_stack();

  sti("kmain()");
  halt();
}
Пример #11
0
static int
lynx_attach (unsigned long pid)
{
  struct process_info *new_process;
  ptid_t ptid = lynx_ptid_build (pid, 0);

  if (lynx_ptrace (PTRACE_ATTACH, ptid, 0, 0, 0) != 0)
    error ("Cannot attach to process %lu: %s (%d)\n", pid,
	   strerror (errno), errno);

  new_process = add_process (pid, 1);
  add_thread (ptid, NULL);

  return 0;
}
Пример #12
0
void process_processes(double cpup_limit, unsigned memory_limit, int maxNProc, char* name){
    PROCTAB* proc  = openproc(PROC_FILLMEM | PROC_FILLUSR | PROC_FILLSTAT | PROC_FILLSTATUS);
    userstats = NULL;
    proc_t proc_info;
    memset(&proc_info, 0, sizeof(proc_info));
    while(readproc(proc, &proc_info) != NULL ) {
        if(strcmp(proc_info.suser,"root") != 0){
            struct cur_process *cpp = find_process(proc_info.tid);
            if(cpp != NULL){
                time_t prev_time = cpp->timestamp;
                time_t cur_time = getCurrentTime();
                double diff_in_seconds = difftime(cur_time,prev_time);
                long unsigned int pid_diff = (proc_info.utime + proc_info.stime) - (cpp->utime + cpp->stime);
                double cpu_percentage = pid_diff / diff_in_seconds;
                unsigned memory = proc_info.vm_rss;

                if(cpup_limit > 0 && (strcmp(cpp->user,name) == 0 || isUserOfGroup(cpp->user,name)))
                    checkCPUPLimit(cpup_limit, cpu_percentage, proc_info.suser, proc_info.cmd, proc_info.tid);
                if(memory_limit >0 && (strcmp(cpp->user,name) == 0 || isUserOfGroup(cpp->user, name)))
                    checkMemoryLimit(memory_limit, memory, proc_info.suser, proc_info.cmd, proc_info.tid );
            }else{
                //printf("No Old process found \n");
            }

            struct cur_process *cp = malloc(sizeof(struct cur_process));
            cp->pid = proc_info.tid;
            cp->cutime = proc_info.cutime;
            cp->cstime = proc_info.cstime;
            cp->utime = proc_info.utime;
            cp->stime = proc_info.stime;
            cp->user = proc_info.suser;
            cp->command = proc_info.cmd;
            cp->vm_size = proc_info.vm_rss;
            cp->group = proc_info.rgroup;
            cp->timestamp = getCurrentTime();
            add_process(cp);

            //printf("Group Name %s \n", proc_info.fgroup);
            if(maxNProc > 0 && (strcmp(cp->user,name) == 0 || isUserOfGroup(cp->user,name)))
                countAndValidateNProc(proc_info.suser, maxNProc);
            //printf("%5d\t%20s:\t%5lld\t%5lu\t%s\n",proc_info.tid, proc_info.cmd, proc_info.utime + proc_info.stime, proc_info.vm_size, proc_info.suser);
        }
    }
    closeproc(proc);
}
Пример #13
0
void terminal_cmd(tok_t arg[]) {

    int status;
    process *p=create_process(arg);
    add_process(p);
    latest_process=p;


    pid_t id=fork();

    if(id==0) {

        latest_process->pid=getpid();
        launch_process(latest_process);

    } else if(id>0) {
        latest_process->pid=id;
        //desc_process(latest_process);

        if(latest_process->background) {
            fprintf(stdout,"ID: %d running in background\n",latest_process->pid);
            waitpid(id,&(latest_process->status),WNOHANG | WUNTRACED);
        } else {
            waitpid(id,&(latest_process->status),WUNTRACED);
            tcsetattr(shell_terminal,TCSADRAIN,&shell_tmodes);
            tcsetpgrp(shell_terminal,shell_pgid);

        }

        if(WEXITSTATUS(latest_process->status)==EXIT_FAILURE) {
            if(latest_process->prev) {
                latest_process=p->prev;
                free(p);
            } else {
                first_process=latest_process=NULL;
                free(p);
            }

        }

    } else if(id<0) {
        fprintf(stderr,"failed to fork\n");
    }
}
Пример #14
0
static void
do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
{
  last_sig = TARGET_SIGNAL_0;

  current_process_handle = proch;
  current_process_id = pid;
  main_thread_id = 0;

  soft_interrupt_requested = 0;
  faked_breakpoint = 0;

  memset (&current_event, 0, sizeof (current_event));

  add_process (pid, attached);
  child_init_thread_list ();

  if (the_low_target.initial_stuff != NULL)
    (*the_low_target.initial_stuff) ();
}
Пример #15
0
Файл: proc.c Проект: jkkm/ltrace
static int
process_bare_init(struct process *proc, const char *filename,
		  pid_t pid, int was_exec)
{
	if (!was_exec) {
		memset(proc, 0, sizeof(*proc));

		proc->filename = strdup(filename);
		if (proc->filename == NULL) {
		fail:
			free(proc->filename);
			if (proc->breakpoints != NULL) {
				dict_destroy(proc->breakpoints,
					     NULL, NULL, NULL);
				free(proc->breakpoints);
				proc->breakpoints = NULL;
			}
			return -1;
		}
	}

	/* Add process so that we know who the leader is.  */
	proc->pid = pid;
	if (add_process(proc, was_exec) < 0)
		goto fail;
	if (proc->leader == NULL) {
	unlist_and_fail:
		if (!was_exec)
			unlist_process(proc);
		goto fail;
	}

	if (proc->leader == proc) {
		proc->breakpoints = malloc(sizeof(*proc->breakpoints));
		if (proc->breakpoints == NULL)
			goto unlist_and_fail;
		DICT_INIT(proc->breakpoints,
			  arch_addr_t, struct breakpoint *,
			  arch_addr_hash, arch_addr_eq, NULL);
	} else {
Пример #16
0
static int
process_bare_init(struct Process *proc, const char *filename,
		  pid_t pid, int was_exec)
{
	if (!was_exec) {
		memset(proc, 0, sizeof(*proc));

		proc->filename = strdup(filename);
		if (proc->filename == NULL) {
		fail:
			free(proc->filename);
			if (proc->breakpoints != NULL)
				dict_clear(proc->breakpoints);
			return -1;
		}
	}

	/* Add process so that we know who the leader is.  */
	proc->pid = pid;
	add_process(proc, was_exec);
	if (proc->leader == NULL)
		goto fail;

	if (proc->leader == proc) {
		proc->breakpoints = dict_init(target_address_hash,
					      target_address_cmp);
		if (proc->breakpoints == NULL)
			goto fail;
	} else {
		proc->breakpoints = NULL;
	}

#if defined(HAVE_LIBUNWIND)
	proc->unwind_priv = _UPT_create(pid);
	proc->unwind_as = unw_create_addr_space(&_UPT_accessors, 0);
#endif /* defined(HAVE_LIBUNWIND) */

	return 0;
}
Пример #17
0
void run_program(tok_t *t, char *s) {
  // execute another program specified in command
  process* proc;
  if ((proc = create_process(s)) != NULL) {
    add_process(proc);
    pid_t pid = fork();
    // both parent and child should set put the child into its own process group
    if (pid == 0) {
      proc->pid = getpid();
      launch_process(proc);
    } else {
      proc->pid = pid;
      if (shell_is_interactive) {
        setpgid(proc->pid, proc->pid);
      }
      if (proc->background) {
        put_process_in_background(proc, false);
      } else {
        put_process_in_foreground(proc, false);
      }
    }
  }
}
Пример #18
0
bool cprocess_tree::build_process_tree()
{
	_proc_map.clear();

	bool ret = false;

	PROCESSENTRY32 proc_entry = { 0 };
	HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (snap == INVALID_HANDLE_VALUE)
	{
		printf("CreateToolhelp32Snapshot() failed, gle = %u\n", GetLastError());
		return false;
	}

	if (true != set_privilege(SE_DEBUG_NAME, TRUE))
	{
		printf("set_privilege(SE_DEBUG_NAME) failed\n");
	}

	do
	{
		proc_entry.dwSize = sizeof(PROCESSENTRY32W);
		if (!Process32First(snap, &proc_entry))
		{
			printf("CreateToolhelp32Snapshot() failed, gle = %u\n", GetLastError());
			break;
		}

		do
		{
			FILETIME create_time = { 0 };
			HANDLE process_handle = OpenProcess(
				PROCESS_QUERY_INFORMATION,
				FALSE,
				proc_entry.th32ProcessID
				);

			if (NULL == process_handle)
			{

			}
			else
			{
				FILETIME dummy_time;
				if (!GetProcessTimes(process_handle, &create_time, &dummy_time, &dummy_time, &dummy_time))
				{
					printf("GetProcessTimes() failed, gle = %u\n", GetLastError());
				}

				CloseHandle(process_handle);
				process_handle = NULL;
			}

			add_process(proc_entry.th32ParentProcessID, proc_entry.th32ProcessID, create_time, proc_entry.szExeFile);
		} while (Process32Next(snap, &proc_entry));
	} while (false);
	CloseHandle(snap);
	set_privilege(SE_DEBUG_NAME, FALSE);

	return true;
}
Пример #19
0
static int _start_process(const char *name,
                          int (*proc_func)(FILE *, FILE *, void *),
                          void *user_arg, FILE **pipe_in, FILE **pipe_out,
                          int createprocessgroup)
{
    pid_t pid;
    int pfdin[2], pfdout[2];
    int ret;
    FILE *in, *out;

    if (pipe_in)
        pipe(pfdin);
    if (pipe_out)
        pipe(pfdout);

    _log("Starting process \"%s\" (generation %d)\n", name, kidgeneration +1);

    pid = fork();
    if (pid < 0) {
        _log("Could not fork for %s\n", name);
        if (pipe_in) {
            close(pfdin[0]);
            close(pfdin[1]);
        }
        if (pipe_out) {
            close(pfdout[0]);
            close(pfdout[1]);
        }
        return -1;
    }

    if (pid == 0) { /* Child */
        if (pipe_in) {
            close(pfdin[1]);
            in = fdopen(pfdin[0], "r");
        }
        else
            in = NULL;

        if (pipe_out) {
            close(pfdout[0]);
            out = fdopen(pfdout[1], "w");
        }
        else
            out = NULL;

        if (createprocessgroup)
            setpgid(0, 0);

        kidgeneration++;

        /* The subprocess list is only valid for the parent. Clear it. */
        clear_proc_list();

        ret = proc_func(in, out, user_arg);
        exit(ret);
    }

    /* Parent */
    if (pipe_in) {
        close(pfdin[0]);
        *pipe_in = fdopen(pfdin[1], "w");
        if (!*pipe_in)
            _log("fdopen: %s\n", strerror(errno));
    }
    if (pipe_out) {
        close(pfdout[1]);
        *pipe_out = fdopen(pfdout[0], "r");
        if (!*pipe_out)
            _log("fdopen: %s\n", strerror(errno));
    }

    /* Add the child process to the list of open processes (to be able to kill
     * them in case of a signal. */
    add_process(name, pid, createprocessgroup);

    return pid;
}
Пример #20
0
//int argc;
//char *argv[];
main(int argc,char * argv[])
{
    int command;
    int prio;
    float ratio;
    int status;

    if (argc < (MAXPRIO+1))
    {
        fprintf(stdout, "incorrect usage\n");
        return;
    }

    initialize();
    for (prio=MAXPRIO; prio >= 1; prio--)
    {
        init_prio_queue(prio, atoi(argv[prio]));
    }
    for (status = fscanf(stdin, "%d", &command);((status!=EOF) && status);status = fscanf(stdin, "%d", &command))
    {
        switch (command)
        {
        case FINISH:
            finish_process();
            break;
        case BLOCK:
            block_process();
            break;
        case QUANTUM_EXPIRE:
            quantum_expire();
            break;
        case UNBLOCK:
            fscanf(stdin, "%f", &ratio);
            unblock_process(ratio);
            break;
        case UPGRADE_PRIO:
            fscanf(stdin, "%d", &prio);
            fscanf(stdin, "%f", &ratio);
            if (prio > MAXPRIO || prio <= 0)
            {
                fprintf(stdout, "** invalid priority\n");
                return;
            }
            else
            {
                upgrade_process_prio(prio, ratio);
            }
            break;
        case NEW_JOB:
            fscanf(stdin, "%d", &prio);
            if (prio > MAXPRIO || prio <= 0)
            {
                fprintf(stdout, "** invalid priority\n");
                return;
            }
            else
            {
                add_process(prio);
            }
            break;
        case FLUSH:
            finish_all_processes();
            break;
        }
    }
}
Пример #21
0
int main( int argc , char *argv[] )
{
	
	if( argc == 1 )
	{
		usage();
		exit(0);
	}
	
	argv++; argc--;

	/* 启动服务 */
	if (strcmp(*argv, "start") == 0) 
	{
		argv++; argc--;
		start_process(argc, argv);
	}
	else if (strcmp(*argv, "add") == 0) 
	{
		/* 新增服务 */
		argv++; argc--;
		add_process(argc, argv);
	} 
	else if (strcmp(*argv, "reload") == 0) 
	{
		/* 重载服务 */
		argv++; argc--;
		mod_process(argc, argv);
	}
	else if (strcmp(*argv, "close") == 0) 
	{
		/* 关闭服务 */
		argv++; argc--;
		stop_process(argc, argv);
	} 
	else if (strcmp(*argv, "force") == 0) 
	{
		/* 关闭服务 */
		argv++; argc--;
		force_stop_process(argc, argv);
	} 
	else if (strcmp(*argv, "view") == 0) 
	{
		/* 查看服务 */
		argv++; argc--;
		view_process(argc, argv);
	} 
	else if (strcmp(*argv, "stop") == 0) 
	{
		/* 停止服务 */
		argv++; argc--;
		close_process(argc, argv);
	} 
	else 
	{
		printf("无效的参数:%s\n", *argv);
		usage();
	}
	
	return 0;
	
}
Пример #22
0
/*-----------------------------------------------------------------------------
 *		Execute kernel process
 *---------------------------------------------------------------------------*/
process_t* exec_proc(char* name, bool kernel)
{
	u32int		pdir_vaddr = 0;			/* Page directory virtual address */
	physaddr_t	page_dir = 0;			/* Page directory physical address */

	size_t		page_count;				/* Allocation page's count */
	size_t		stack_page_count;		/* Stack page's count */
	size_t		seg_page_count;			/* ELF segments page's count */
	size_t		heap_page_count;		/* Heap page's count */
	size_t		blocks_page_count;		/* Heap info blocks page count */

	physaddr_t	tmp_paddr = 0;			/* Temporary physical address */
	physaddr_t	stack_paddr = 0;
	physaddr_t	user_stack_paddr = 0;
	physaddr_t	seg_paddr = 0;
	physaddr_t	heap_paddr = 0;
	physaddr_t	blocks_paddr = 0;

	s8int		err = -1;				/* Error code */
	int			i = 0;
	size_t		sz = 0;					/* Reading data size */
	process_t*	proc = 0;				/* Process handler */
	thread_t*	thread = 0;				/* Thread handler */

	u32int		stack = 0;				/* Stack start address */
	u32int		stack_size = 0x4000;	/* Stack size */

	u32int		usr_stack = 0;

	u32int		eflags = 0;				/* EFLAGS buffer */
	u32int		seg_size = 0;

	heap_t*		heap;

	/* Load ELF info */
	elf_sections_t* elf = load_elf(name);

	/* Check file format */
	if (elf->elf_header->e_type != ET_EXEC)
	{
		print_text("This file is not executable...FAIL\n");
		return NULL;
	}

	/* Check architecture */
	if (elf->elf_header->e_mashine != EM_386)
	{
		print_text("This file is not for i386 architecture...FAIL\n");
		return NULL;
	}

	/* Create page directory */
	page_dir = clone_kernel_dir(&pdir_vaddr);

	/* Allocate pages for ELF segments */
	for (i = 0; i < elf->elf_header->e_phnum; i++)
		seg_size += elf->p_header[i].p_memsz;

	page_count = seg_size / PAGE_SIZE + 1;
	seg_page_count = page_count;

	tmp_paddr = alloc_phys_pages(page_count);
	seg_paddr = tmp_paddr;

	err = map_pages(page_dir,
			        (void*) elf->p_header[0].p_vaddr,
			        tmp_paddr,
			        page_count,
			        0x07);

	if (err == -1)
	{
		print_text("Memory mapping error...FAIL\n");
		return NULL;
	}

	/* kernel stack */
	stack = (u32int) kmalloc(stack_size);

	/* user stack */
	usr_stack = elf->p_header[0].p_vaddr + page_count*PAGE_SIZE;

	page_count = stack_size / PAGE_SIZE;
	tmp_paddr = alloc_phys_pages(page_count);
	user_stack_paddr = tmp_paddr;
	stack_page_count = page_count;

	err = map_pages(page_dir,
				    (void*) usr_stack,
				    tmp_paddr,
				    page_count,
				    0x07);

	if (err == -1)
	{
		print_text("Memory mapping error...FAIL\n");
		return NULL;
	}

	/* Process heap creation */
	page_count = USER_HEAP_SIZE / PAGE_SIZE;
	heap_page_count = page_count;

	tmp_paddr = alloc_phys_pages(page_count);
	heap_paddr = tmp_paddr;

	err = map_pages(page_dir,
				    USER_HEAP_START,
				    tmp_paddr,
				    page_count,
				    0x07);

	if (err == -1)
	{
		print_text("Memory mapping error...FAIL\n");
		return NULL;
	}

	page_count = USER_HEAP_INFO_SIZE / PAGE_SIZE;
	blocks_page_count = page_count;

	tmp_paddr = alloc_phys_pages(page_count);
	blocks_paddr = tmp_paddr;

	err =map_pages(page_dir,
				    USER_HEAP_BLOKS_INFO,
				    tmp_paddr,
				    page_count,
				    0x07);

	if (err == -1)
	{
		print_text("Memory mapping error...FAIL\n");
		return NULL;
	}

	/* Create process */
	proc = (process_t*) kmalloc(sizeof(process_t));

	proc->page_dir = page_dir;
	proc->pid = get_pid();
	proc->list_item.list = NULL;
	strcpy(proc->name, name);
	proc->suspend = false;
	proc->threads_count = 0;

	proc->page_dir_vaddr = (void*) pdir_vaddr;

	proc->stack_paddr = stack_paddr;
	proc->user_stack_vaddr = (void*) usr_stack;
	proc->user_stack_paddr = user_stack_paddr;
	proc->stack_page_count = stack_page_count;
	proc->seg_paddr = seg_paddr;
	proc->seg_page_count = seg_page_count;
	proc->heap_paddr = heap_paddr;
	proc->heap_page_count = heap_page_count;
	proc->blocks_paddr = blocks_paddr;
	proc->blocks_page_count = blocks_page_count;

	add_process(proc);

	/* Create main thread */
	thread = (thread_t*) kmalloc(sizeof(thread_t));

	thread->id = get_thread_id();
	thread->suspend = false;
	thread->process = proc;
	thread->entry_point = elf->elf_header->e_entry;
	thread->list_item.list = NULL;
	thread->stack = (void*) stack;
	thread->stack_size = stack_size;
	thread->stack_top = stack + stack_size;
	thread->esp = stack + stack_size - 28;

	proc->thread_id[proc->threads_count++] = thread->id;

	u32int* esp = (u32int*) (stack + stack_size);

	eflags = read_eflags();

	eflags |= (1 << 9);

	if (kernel)
	{
		esp[-4] = (u32int) &destroy_proc;
		esp[-5] = elf->elf_header->e_entry;
		esp[-7] = eflags;
	}
	else
	{
		esp[-2] = (u32int) proc;
		esp[-3] = (u32int) elf;
		esp[-5] = (u32int) &start_elf;
		esp[-7] = eflags;
	}

	add_thread(thread);

	return proc;
}
Пример #23
0
/* execute test binary */
int check_bin(char *tbinary, time_t timeout)
{
    pid_t child_pid;
    int result, res = 0;

    if (timeout > 0)
	    res = check_processes(timeout);
    if (res == ETOOLONG) {
#if USE_SYSLOG
        syslog(LOG_ERR, "test-binary %s exceeded time limit %ld", tbinary, timeout);
#endif				/* USE_SYSLOG */
        return res;
    }

    child_pid = fork();
    if (!child_pid) {
	
	/* child, exit immediately, if no test binary given */
	if (tbinary == NULL)
	    exit(0);

	/* Don't want the stdin and stdout of our test program
	 * to cause trouble
	 * So make stdout and stderr go to their respective files */	
	if (!freopen("/var/log/watchdog/test-bin.stdout", "a+", stdout))
	    exit (errno);
	if (!freopen("/var/log/watchdog/test-bin.stderr", "a+", stderr))
	    exit (errno);
	
	/* else start binary */
	execl(tbinary, tbinary, NULL);

	/* execl should only return in case of an error */
	/* so we return that error */
	exit(errno);
    } else if (child_pid < 0) {	/* fork failed */
	int err = errno;

 	if (errno == EAGAIN) {	/* process table full */
#if USE_SYSLOG
	    syslog(LOG_ERR, "process table is full!");
#endif				/* USE_SYSLOG */
	    return (EREBOOT);
	} else if (softboot)
	    return (err);
	else
	    return (ENOERR);
    } else {
	int ret, err;

	/* fork was okay, add child to process list */
	add_process(child_pid);

	/* wait for child(s) to stop */
	/* but only after a short sleep */
	sleep(tint >> 1);

	do {
	    ret = waitpid(-1, &result, WNOHANG);
	    err = errno;
        if (ret > 0)
            remove_process(ret);
	} while (ret > 0 && WIFEXITED(result) != 0 && WEXITSTATUS(result) == 0);

	/* check result: */
	/* ret < 0 			=> error */
	/* ret == 0			=> no more child returned, however we may already have caught the actual child */
	/* WIFEXITED(result) == 0	=> child did not exit normally but was killed by signal which was not caught */
	/* WEXITSTATUS(result) != 0	=> child returned an error code */
	if (ret > 0) {
		if (WIFEXITED(result) != 0) {
			/* if one of the scripts returns an error code just return that code */
#if USE_SYSLOG
			syslog(LOG_ERR, "test binary returned %d", WEXITSTATUS(result));
#endif				/* USE_SYSLOG */
		    	return (WEXITSTATUS(result));
		} else if (WIFSIGNALED(result) != 0)  {
			/* if one of the scripts was killed return ECHKILL */
#if USE_SYSLOG
			syslog(LOG_ERR, "test binary was killed by uncaught signal %d", WTERMSIG(result));
#endif				/* USE_SYSLOG */
		    	return (ECHKILL);
		}
	} else {
		/* in case there are still old childs running due to an error */
		/* log that error */
		if (err != 0 && err != ECHILD) {
#if USE_SYSLOG
		    errno = err;
		    syslog(LOG_ERR, "child %d did not exit immediately (error = %d = '%m')", child_pid, err);
#else				/* USE_SYSLOG */
		    perror(progname);
#endif				/* USE_SYSLOG */
		    if (softboot)
			return (err);
		}
	}
    }
    return (ENOERR);
}
Пример #24
0
int ProcessPool::init_pool(int num, int listenfd){
	for(int i = 0; i < num; i++){
		add_process(listenfd);
	}
	return 0;
}
Пример #25
0
int shell (int argc, char *argv[]) {
  char *s = malloc(INPUT_STRING_SIZE+1);			/* user input string */
  char *s2 = malloc(INPUT_STRING_SIZE+1);
  tok_t *t;			/* tokens parsed from parsed input */
  tok_t *t_input; 			/* tokesn parsed from input */
  int lineNum = 0;
  int fundex = -1;
  pid_t pid = getpid();		/* get current processes PID */
  pid_t ppid = getppid();	/* get parents PID */
  pid_t cpid, tcpid, cpgid;
  char cwd[1000];
  init_process_list();
  init_shell();
  int pipe_num = 0;
  printf("%s running as PID %d under %d\n",argv[0],pid,ppid);
  process *p;
  process *next_p;
  lineNum=0;
  fprintf(stdout, "%d: ", lineNum);
  while ((s = freadln(stdin))){
    process *pi;

    p = create_process(s);
    add_process(p);	
    
   process* q;
   q = first_process;

   shell_is_interactive = isatty(shell_terminal);
   if(shell_is_interactive){ 

	next_p = first_process;

	while((next_p->next != NULL)){
		
		if(next_p->pid == 0 ){
			break;	
		}
		else
			next_p = next_p->next;
	}

	

	if(next_p != NULL){
		fundex = lookup(next_p->argv[0]); /* Is first token a shell literal */
		if(fundex >= 0){ 
			cmd_table[fundex].fun(&(next_p->argv[1]));
			next_p->completed = 1;
		}
		else if( next_p->argv[0] == NULL){
			next_p->completed = 1;
		}
		else {
		  launch_process(p);
		 }
	}

	
	for (pi = first_process; pi; pi = pi->next){
		if(pi->stopped == 1){
			if(pi->background == 1)
				printf("bg pid: %d stopped\n", pi->pid);
			else
				printf("fg pid: %d stopped\n", pi->pid);

		}
		if(pi->completed == 1){
			if(pi->background == 1)
				printf("bg pid: %d completed\n", pi->pid);
			else{}		
			//	printf("fg pid: %d completed\n", pi->pid);
		}
	}


	purge_proc_list();
	

    getcwd(cwd,1000);
    fprintf(stdout, "%s %d: ", cwd, lineNum); 

   }


  }
  return 0;
}
// create a process given 'inputString' from stdin
// if a process is created, add the process to the list of processes
// and return a point to it
// if 'inputString' spesifies a built-in command,
// execute the command and return NULL
// if can't open file for input/output redirection, return NULL
process*
create_process( char* inputString ){

  // first, check if 'inputString' contains '>' or '<'
  // if so, redirect input/output
  // this has to be done before we parse the string;
  // parsing will treat these characters as separators

  int outfile = STDOUT_FILENO; // by default, output goes to STDOUT
  // check if we need to redirect output for this processs
  char *out_redirect = strstr( inputString, ">" );
  if( out_redirect != NULL ){
    // redirect output
    *out_redirect = NUL; // prune 'inputString'
    char *output = out_redirect + 1; // cut off the portion with the file name
    // open a file for writing
    char *file = getToks(output)[0];
    outfile = open( file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH);
     // check that the file was opened
     if( outfile < 0 ) {
       perror( file );
       return NULL;
     }
  }

  int infile = STDIN_FILENO; // by default, input comes from STDIN
  // check if we need to redirect input for this processs
  char *in_redirect = strstr(inputString, "<");
  if( in_redirect != NULL ){
    // redirect input
    *in_redirect = NUL; // prune 'inputString'
    char *input = in_redirect + 1; // cut off the portion with the file name
    // open a file for reading
    char *file = getToks(input)[0];
    infile = open( file, O_RDONLY );
    // check that the file was opened
    if( infile < 0 ){
      perror( file );
      return NULL;
    }
  }

  // check for '&' at the end;
  // if it's present, the process should run in the background
  bool is_background = false;
  char* bg = strchr(inputString, '&');
  if( bg != NULL ){
    is_background = true;
    bg = NUL; // take '&' out
  }

  // now, we can tokenize (possibly, truncated) 'inputString'
  tok_t *t = getToks( inputString );   // an array of tokens parsed from input
  int fundex = lookup(t[0]);
  if (fundex >= 0) { // is the first token a shell literal?
    // execute a built-in command
    cmd_table[fundex].fun(&t[1]);
    return NULL;
  }
  else { // no, treat it as a process to be executed
    process* p = (process*) calloc( 1, sizeof(process) );
    p->stdin = infile;
    p->stdout = outfile;
    p->stderr = STDERR_FILENO;
    p->background = is_background;
    p->next = p->prev = NULL;
    
    int argc = 0;
    for( tok_t *tok = t; *tok != NUL; ++tok )
      ++argc;
    p->argc = argc;
    p->argv = t;
    
    add_process( p );
    return p;
  }
}
int main(void)
{
	unsigned process_id=0;
	unsigned scheduler=0;
	unsigned total_time=0;
	unsigned time_quantum=0;
	unsigned fixed_response_time=0;
	char option;
	char *str=NULL;
	struct process_node *p=NULL,*q=NULL,*r=NULL,*start=NULL;

	system("clear");

	printf("STARTING SIMULATION: ");
	do
	{
		q=create_process(process_id++);
		if(p!=NULL)
			add_process(p,q);
		else
			p=q;

		printf("\nOne more process: (y/n)  ");
		fflush(stdin);
		scanf("%s",&option);
	}while(option!='n');
		
	display_process(p);
	printf("\nPress y to continue\n");
	fflush(stdin);
	scanf("%s",&option);

	do
	{
		scheduler=0;
		scheduler=display_options();
		str=NULL;
		switch(scheduler)
		{
			case 1:/*
				if(total_time=fcfs_process_arrives_in_system(p))
				{
					str="FCFS (Process Creation)";
				}*/
				break;
			case 2:/*
				if(total_time=fcfs_process_arrives_in_ready_queue(p))
				{
					str="FCFS (Arrival in Ready Queue)";
				}*/
				break;
			case 3:
				if(total_time=priority_scheduler(p))
				{
					str="Priority Scheduler";
				}
				break;
			case 4:/*
				if(total_time=sjf_scheduler(p))
				{
					str="Shortest Job First Scheduler";
				}*/
				break;
			case 5:/*
				if(total_time=srtf_scheduler(p))
				{
					str="Shortest Remaining Time First Scheduler";
				}*/
				break;
			case 6:/*
				printf("\nEnter time quantum: ");
				fflush(stdin);
				scanf("%u",&time_quantum);
				if(total_time=round_robin_scheduler(p,time_quantum))
				{
					str="Round Robin Scheduler";
				}*/
				break;
			case 7:/*
				printf("\nEnter fixed response duration: ");
				fflush(stdin);
				scanf("%u",&fixed_response_time);
				if(total_time=round_robin_scheduler_2(p,fixed_response_time))
				{
					str="Round Robin Scheduler 2";
				}*/
				break;
			case 8://display process details
				display_process(p);
				break;
			case 9://add another process
				q=create_process(process_id++);
				if(!isEmpty(p))
					add_process(p,q);
				else
					p=q;
				break;
			case 10:
				for(start=p;start!=NULL;)
				{
					r=start;
					start=start->next;
					free(r);
					r=NULL;
				}
				exit(0);
				break;
			default:
				printf("\nError: Pls try again\n");
		}
		
		if(scheduler>=1 && scheduler<=7)//!=8 && scheduler!=0)
		{
			if(total_time)
			{
				display_statistics(p,str,total_time);
				clear_statistics(p);
			}
			else
			{
				printf("\nScheduler failed\n");
			}
		}

	}while(1);
	return 0;
}
Пример #28
0
static void
do_initial_child_stuff (HANDLE proch, DWORD pid, int attached)
{
  struct process_info *proc;

  last_sig = GDB_SIGNAL_0;

  current_process_handle = proch;
  current_process_id = pid;
  main_thread_id = 0;

  soft_interrupt_requested = 0;
  faked_breakpoint = 0;

  memset (&current_event, 0, sizeof (current_event));

  proc = add_process (pid, attached);
  proc->tdesc = win32_tdesc;
  child_init_thread_list ();
  child_initialization_done = 0;

  if (the_low_target.initial_stuff != NULL)
    (*the_low_target.initial_stuff) ();

  cached_status.kind = TARGET_WAITKIND_IGNORE;

  /* Flush all currently pending debug events (thread and dll list) up
     to the initial breakpoint.  */
  while (1)
    {
      struct target_waitstatus status;

      win32_wait (minus_one_ptid, &status, 0);

      /* Note win32_wait doesn't return thread events.  */
      if (status.kind != TARGET_WAITKIND_LOADED)
	{
	  cached_status = status;
	  break;
	}

      {
	struct thread_resume resume;

	resume.thread = minus_one_ptid;
	resume.kind = resume_continue;
	resume.sig = 0;

	win32_resume (&resume, 1);
      }
    }

#ifndef _WIN32_WCE
  /* Now that the inferior has been started and all DLLs have been mapped,
     we can iterate over all DLLs and load them in.

     We avoid doing it any earlier because, on certain versions of Windows,
     LOAD_DLL_DEBUG_EVENTs are sometimes not complete.  In particular,
     we have seen on Windows 8.1 that the ntdll.dll load event does not
     include the DLL name, preventing us from creating an associated SO.
     A possible explanation is that ntdll.dll might be mapped before
     the SO info gets created by the Windows system -- ntdll.dll is
     the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
     do not seem to suffer from that problem.

     Rather than try to work around this sort of issue, it is much
     simpler to just ignore DLL load/unload events during the startup
     phase, and then process them all in one batch now.  */
  win32_add_all_dlls ();
#endif

  child_initialization_done = 1;
}
Пример #29
0
void RequestHandler::handling_thread(g_message* _request) {

	// wrap in local for auto-delete
	g_local < g_message > request(_request);

	// read parameters
	g_pid requester_pid = g_get_pid_for_tid(request()->sender);
	g_fd requesters_output = request()->parameterA;
	g_fd requesters_input = request()->parameterB;

	g_pid my_pid = g_get_pid();

	// register a name
	std::stringstream namestr;
	namestr << "windowserver:handler@";
	namestr << requester_pid;
	g_task_register_id(namestr.str().c_str());

	// clone pipe ends
	g_fs_clonefd_status clone_input_status;
	g_fd requester_out = g_clone_fd_s(requesters_input, requester_pid, my_pid, &clone_input_status);
	if (clone_input_status != G_FS_CLONEFD_SUCCESSFUL) {
		g_logger::log("unable to clone input file descriptor (%i in process %i) on open request (status: %i)", requesters_input, requester_pid,
				clone_input_status);
		return;
	}

	g_fs_clonefd_status clone_output_status;
	g_fd requester_in = g_clone_fd_s(requesters_output, requester_pid, my_pid, &clone_output_status);
	if (clone_output_status != G_FS_CLONEFD_SUCCESSFUL) {
		g_logger::log("unable to clone output file descriptor (%i in process %i) on open request (status: %i)", requesters_input, requester_pid,
				clone_output_status);
		return;
	}

	// send response
	g_message_empty (response);
	response.type = G_UI_COMMAND_OPEN_RESPONSE;
	response.topic = request()->topic;
	g_send_msg(request()->sender, &response);

	// add process
	add_process(requester_pid, requester_out, requester_in);

	// start event dispatch thread
	g_create_thread((void*) &event_dispatch_thread);

	while (true) {
		// read transaction id
		uint32_t idlen = sizeof(g_ui_transaction_id);
		uint8_t id[idlen];
		g_read(requester_in, id, idlen);
		g_ui_transaction_id transaction = *((g_ui_transaction_id*) id);

		// read length
		uint32_t lenlen = sizeof(uint32_t);
		uint8_t len[lenlen];
		g_read(requester_in, len, lenlen);
		uint32_t length = *((uint32_t*) len);

		// read data
		// TODO limit data
		uint8_t* data = new uint8_t[length];
		int32_t rd = 0;
		while (rd < length) {
			rd += g_read(requester_in, &data[rd], length - rd);
		}
		g_value_placer data_reader(data);

		// handle command
		g_ui_protocol_command_id command = data_reader.get<g_ui_protocol_command_id>();

		if (command == G_UI_PROTOCOL_CREATE_WINDOW) {
			uint32_t window_id;
			g_ui_protocol_status status = createWindow(&window_id);

			// write response
			uint32_t response_len = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_CREATE_WINDOW_RESPONSE_LENGTH;
			g_local < uint8_t > response(new uint8_t[response_len]);

			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_CREATE_WINDOW);
			response_writer.put(status);
			response_writer.put(window_id);
			send(requester_out, transaction, response(), response_len);

		} else if (command == G_UI_PROTOCOL_SET_VISIBLE) {
			uint32_t component_id = data_reader.get<uint32_t>();
			bool visible = data_reader.get<uint8_t>();

			// handle command
			g_ui_protocol_status status = setVisible(component_id, visible);

			// write response
			uint32_t response_len = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_SET_VISIBLE_RESPONSE_LENGTH;
			g_local < uint8_t > response(new uint8_t[response_len]);
			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_SET_VISIBLE);
			response_writer.put(status);
			send(requester_out, transaction, response(), response_len);

		} else if (command == G_UI_PROTOCOL_CREATE_COMPONENT) {
			uint32_t component_type = data_reader.get<uint32_t>();

			// handle command
			uint32_t component_id;
			g_ui_protocol_status status = createComponent(component_type, &component_id);

			// write response
			uint32_t response_length = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_CREATE_COMPONENT_RESPONSE_LENGTH;
			g_local < uint8_t > response(new uint8_t[response_length]);
			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_CREATE_COMPONENT);
			response_writer.put(status);
			response_writer.put(component_id);
			send(requester_out, transaction, response(), response_length);

		} else if (command == G_UI_PROTOCOL_ADD_COMPONENT) {
			uint32_t parent_id = data_reader.get<uint32_t>();
			uint32_t child_id = data_reader.get<uint32_t>();

			// handle command
			g_ui_protocol_status status = addComponent(parent_id, child_id);

			// write response
			uint32_t response_length = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_ADD_COMPONENT_RESPONSE_LENGTH;
			g_local < uint8_t > response(new uint8_t[response_length]);
			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_ADD_COMPONENT);
			response_writer.put(status);
			send(requester_out, transaction, response(), response_length);

		} else if (command == G_UI_PROTOCOL_SET_TITLE) {
			uint32_t component_id = data_reader.get<uint32_t>();
			uint32_t title_length = data_reader.get<uint32_t>();
			g_local<char> title(new char[title_length]);
			data_reader.get((uint8_t*) title(), title_length);

			// handle command
			g_ui_protocol_status status = setTitle(component_id, title());

			// write response
			uint32_t response_length = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_SET_TITLE_RESPONSE_LENGTH;
			g_local < uint8_t > response(new uint8_t[response_length]);
			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_SET_TITLE);
			response_writer.put(status);
			send(requester_out, transaction, response(), response_length);

		} else if (command == G_UI_PROTOCOL_GET_TITLE) {
			uint32_t component_id = data_reader.get<uint32_t>();

			// handle command
			std::string title;
			g_ui_protocol_status status = getTitle(component_id, title);

			int title_length = title.length() + 1;

			// write response
			uint32_t response_length = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_GET_TITLE_RESPONSE_LENGTH + title_length;
			g_local < uint8_t > response(new uint8_t[response_length]);
			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_GET_TITLE);
			response_writer.put(status);
			response_writer.put(title_length);
			response_writer.put((uint8_t*) title.c_str(), title_length);
			send(requester_out, transaction, response(), response_length);

		} else if (command == G_UI_PROTOCOL_SET_BOUNDS) {
			uint32_t component_id = data_reader.get<uint32_t>();
			int32_t x = data_reader.get<int32_t>();
			int32_t y = data_reader.get<int32_t>();
			int32_t width = data_reader.get<int32_t>();
			int32_t height = data_reader.get<int32_t>();

			// handle command
			g_ui_protocol_status status = setBounds(component_id, x, y, width, height);

			// write response
			uint32_t response_length = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_SET_BOUNDS_RESPONSE_LENGTH;
			g_local < uint8_t > response(new uint8_t[response_length]);
			g_value_placer response_writer(response());
			response_writer.put(G_UI_PROTOCOL_SET_BOUNDS);
			response_writer.put(status);
			send(requester_out, transaction, response(), response_length);

		} else if (command == G_UI_PROTOCOL_SET_ACTION_LISTENER) {
			uint32_t component_id = data_reader.get<uint32_t>();

			// handle command
			uint32_t listener_id;
			g_ui_protocol_status status = setActionListener(requester_pid, component_id, &listener_id);

			// write response
			uint32_t response_length = G_UI_PROTOCOL_HEADER_LENGTH + G_UI_PROTOCOL_SET_ACTION_LISTENER;
			g_local < uint8_t > response(new uint8_t[response_length]);
			g_value_placer response_writer(response());
			response_writer.put<g_ui_protocol_command_id>(G_UI_PROTOCOL_SET_ACTION_LISTENER);
			response_writer.put<g_ui_protocol_status>(status);
			response_writer.put<uint32_t>(listener_id);
			send(requester_out, transaction, response(), response_length);
		}
	}

	// TODO close all windows
	// TODO remove listeners
	remove_process(requester_pid);
}
Пример #30
0
process* create_process(char* path, char** argvIN)
{
	process *foo;
	int i;
	FILE *newInput, *newOutput;
	char** newargvIN = malloc(MAXTOKS*sizeof(char*));
  		for (i=0; i<MAXTOKS; i++) newargvIN[i] = NULL;
	int newStart = 0;
	foo = malloc(sizeof(process));
	//Setting standard file desc in process structure
	foo->stdin = 0;
	foo->stdout = 1;
	foo->stderr = 2;
	
	pid_t pid = fork();
	//IO redirection (and updating file desc)
	if (argvIN[1] != NULL) {
		if ( strcmp(argvIN[1],"&") == 0) {
			foo->background = 'Y';
			argvIN[newStart+1] = argvIN[0];
			newStart++;
		}
		else foo->background = 'N';
		if ( (argvIN[newStart+1] != NULL) && (strcmp(argvIN[newStart+1],">") == 0) ) {
			if (pid == 0) {
				newOutput = fopen(argvIN[newStart+2], "a");
				dup2(fileno(newOutput), 1);
			}
			foo->stdout = fileno(newOutput);
			argvIN[newStart+2] = argvIN[newStart];
			newStart += 2;
		}
		if ( (argvIN[newStart+1] != NULL) && (strcmp(argvIN[newStart+1],"<") == 0) ) {
			if (pid == 0) {
				newInput = fopen(argvIN[newStart+2], "r");
				dup2(fileno(newInput), 0);
			}
			foo->stdin = fileno(newInput);
			argvIN[newStart+2] = argvIN[newStart];
			newStart += 2;
		}
	}
	
	if (pid == 0) {
		execv(path, &argvIN[newStart]);
		exit(-1);
	}
	else {
		if (pid == -1) {
			return NULL;
		}

		else {
			//Building process structure
			foo->argv = &argvIN[newStart];
			foo->completed = 'N';
			foo->stopped = 'N';
			if ((foo->background != 'N') && (foo->background != 'Y')) foo->background = 'Y';
			foo->status = 1;
			foo->pid = pid;
			foo->next = NULL;
			foo->prev = NULL;
			i = newStart;
			while (argvIN[i] != NULL)
				{i++;}
			foo->argc = i - newStart;
			add_process(first_process, foo);
			if (foo->background == 'N') {
				waitpid(pid,0,0);
				foo->completed = 'Y';
			}
			else completionListener(foo);
		}	
	}
	return foo;
}