示例#1
0
gint create_gnomeprint_session(void)
{
    GnomePrintJob *job = NULL;
    static GnomePrintConfig *gpc = NULL;
    GtkWidget *dialog, *preview;
    gint res, page_num = 0;
    GtkWidget *notebook, *page;

    if (gpc == NULL)
        gpc = gnome_print_config_default();

    job = gnome_print_job_new(gpc);
    if (job == NULL)
        return -1;

    dialog = gnome_print_dialog_new(job, (guchar *)_("Print"), 0);
    notebook = gtk_container_get_children(
                   GTK_CONTAINER(GTK_DIALOG(dialog)->vbox))->data;
    gtk_widget_hide(notebook);
    if (!GTK_WIDGET_VISIBLE(gtk_notebook_get_nth_page(GTK_NOTEBOOK(notebook), page_num)))
        page_num++;
    page = gtk_widget_ref(
               gtk_notebook_get_nth_page(GTK_NOTEBOOK(notebook), page_num));
    gtk_notebook_remove_page(GTK_NOTEBOOK(notebook), page_num);
    gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox),
                       page, FALSE, FALSE, 0);
    gtk_widget_set_size_request(
        gtk_container_get_children(GTK_CONTAINER(page))->data, -1, 240);
    gtk_window_set_transient_for(GTK_WINDOW(dialog),
                                 GTK_WINDOW(pub->mw->window));

    do {
        res = gtk_dialog_run(GTK_DIALOG(dialog));
        gnome_print_config_unref(gpc);
        gpc = gnome_print_dialog_get_config(GNOME_PRINT_DIALOG(dialog));
        switch (res) {
        case GNOME_PRINT_DIALOG_RESPONSE_PRINT:
            g_object_unref(job);
            job = create_job(gpc);
            gnome_print_job_print(job);
            break;
        case GNOME_PRINT_DIALOG_RESPONSE_PREVIEW:
            g_object_unref(job);
            job = create_job(gpc);
            preview = gnome_print_job_preview_new(job,
                                                  (guchar *)_("Print Preview"));
//			gtk_window_set_transient_for(GTK_WINDOW(preview), GTK_WINDOW(dialog));
            gtk_window_set_modal(GTK_WINDOW(preview), TRUE);
            gtk_widget_show(preview);
            g_signal_connect(G_OBJECT(preview), "destroy",
                             G_CALLBACK(gtk_main_quit), NULL);
            gtk_main();
            break;
        }
    } while (res == GNOME_PRINT_DIALOG_RESPONSE_PREVIEW);
    gtk_widget_destroy(dialog);
    g_object_unref(job);

    return res;
}
示例#2
0
void	token_linker(t_shell *sh, t_job **job, t_process **p, t_token *token)
{
	create_process(p, token, sh);
	create_job(job, p, token);
	init_stdio(sh);
	*p = NULL;
}
示例#3
0
int wproc_run(int jtype, char *cmd, int timeout, nagios_macros *mac)
{
	struct wproc_job *job;

	job = create_job(jtype, NULL, timeout, cmd);
	return wproc_run_job(job, mac);
}
示例#4
0
文件: workers.c 项目: atj/nagios
int wproc_run(int jtype, char *cmd, int timeout, nagios_macros *mac)
{
	worker_job *job;
	time_t real_timeout = timeout + time(NULL);

	job = create_job(jtype, NULL, real_timeout, cmd);
	return wproc_run_job(job, mac);
}
示例#5
0
文件: workers.c 项目: atj/nagios
int wproc_run_service_job(int jtype, int timeout, service *svc, char *cmd, nagios_macros *mac)
{
	worker_job *job;
	wproc_object_job *oj;

	oj = create_object_job(NULL, svc->host_name, svc->description);
	job = create_job(jtype, oj, timeout, cmd);

	return wproc_run_job(job, mac);
}
示例#6
0
文件: workers.c 项目: atj/nagios
int wproc_run_host_job(int jtype, int timeout, host *hst, char *cmd, nagios_macros *mac)
{
	worker_job *job;
	wproc_object_job *oj;

	oj = create_object_job(NULL, hst->name, NULL);
	job = create_job(jtype, oj, timeout, cmd);

	return wproc_run_job(job, mac);
}
示例#7
0
文件: workers.c 项目: atj/nagios
int wproc_notify(char *cname, char *hname, char *sdesc, char *cmd, nagios_macros *mac)
{
	worker_job *job;
	wproc_object_job *oj;

	oj = create_object_job(cname, hname, sdesc);
	job = create_job(WPJOB_NOTIFY, oj, notification_timeout, cmd);

	return wproc_run_job(job, mac);
}
示例#8
0
int wproc_run_host_job(int jtype, int timeout, host *hst, char *cmd, nagios_macros *mac)
{
	struct wproc_job *job;
	wproc_object_job *oj;

	if (!(oj = create_object_job(NULL, hst->name, NULL)))
		return ERROR;

	job = create_job(jtype, oj, timeout, cmd);

	return wproc_run_job(job, mac);
}
示例#9
0
int wproc_run_check(check_result *cr, char *cmd, nagios_macros *mac)
{
	struct wproc_job *job;
	int timeout;

	if (cr->service_description)
		timeout = service_check_timeout;
	else
		timeout = host_check_timeout;

	job = create_job(WPJOB_CHECK, cr, timeout, cmd);
	return wproc_run_job(job, mac);
}
示例#10
0
int wproc_run_callback(char *cmd, int timeout,
		void (*cb)(struct wproc_result *, void *, int), void *data,
		nagios_macros *mac)
{
	struct wproc_job *job;
	struct wproc_callback_job *cj;
	if (!(cj = calloc(1, sizeof(*cj))))
		return ERROR;
	cj->callback = cb;
	cj->data = data;

	job = create_job(WPJOB_CALLBACK, cj, timeout, cmd);
	return wproc_run_job(job, mac);
}
示例#11
0
文件: input.c 项目: SOII-2016/shue
void try_pipeline(const char *line)
{
        job_t *job;             /* Job iterator */
        char *ctok, *ccon;      /* Command token, command context */

        /* Copy string to safe memory area */
        char *str = malloc(strlen(line) + 1);
        strcpy(str, line);

        /**/
        ctok = strtok_r(str, CMD_BG, &ccon);
        while (ctok != NULL) {

                char *ptok, *pcon; /* Process token, process context*/

                job = create_job(shell_pgid);
                job->command = malloc(strlen(ctok) + 1);
                strcpy(job->command, ctok);

                /**/
                ptok = strtok_r(ctok, CMD_PIPE, &pcon);
                while (ptok != NULL) {

                        char *argv[CMD_MAXARGV], *acon; /* Argument vector, argument context */

                        /**/
                        int i = 0;
                        argv[i++] = strtok_r(ptok, CMD_DELIM, &acon);
                        while ((i < CMD_MAXARGV) && (argv[i++] = strtok_r(NULL, CMD_DELIM, &acon)));
                        create_process(job, argv);

                        ptok = strtok_r(NULL, CMD_PIPE, &pcon);
                }
                ctok = strtok_r(NULL, CMD_BG, &ccon);
        }

        /* Launch all created jobs */
        job = first_job;
        for (; job != NULL; job = job->next)
                if (job->next != NULL)
                        sh_launch_job(job, 0);
                else
                        sh_launch_job(job, 1);
        job_do_notify();

        /* Free safe memory area */
        free(str);
}
示例#12
0
/**
	Called when a new job arrives.
 
	If multiple cores are idle, the job should be assigned to the core with the
	lowest id.
	If the job arriving should be scheduled to run during the next
	time cycle, return the zero-based index of the core the job should be
	scheduled on. If another job is already running on the core specified,
	this will preempt the currently running job.
	Assumptions:
		- You may assume that every job wil have a unique arrival time.
	@param job_number a globally unique identification number of the job arriving.
	@param time the current time of the simulator.
	@param running_time the total number of time units this job will run before it will be finished.
	@param priority the priority of the job. (The lower the value, the higher the priority.)
	@return index of core job should be scheduled on
	@return -1 if no scheduling changes should be made. 
 
 */
int scheduler_new_job(int job_number, int time, int running_time, int priority)
{
	int i;
	inc_time(time);
	job_t* job = create_job(job_number, time, running_time, priority);

	if ( (i = get_core()) != -1 )
	{
		insert_job(i,job);
		return i;
	}//if
	else if ( is_prempt() )
	{
		i = preempt(job);
		if ( i == -1 )
			priqueue_offer(jobs,job);
		return i;
	}//else if
	priqueue_offer(jobs,job);
	return -1;
}//scheduler_new_job
示例#13
0
pwr_tStatus
ini_PlcStart (
    pwr_tUInt32		plcversion
)
{
    pwr_tStatus		sts;
    PORT			jobport;
    char			progname[80];
    struct dsc$descriptor	prognamedsc;

    /* Build program name.  */

    sprintf(progname, PLC_NAME, plcversion, loadcount);
    prognamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
    prognamedsc.dsc$b_class = DSC$K_CLASS_S;
    prognamedsc.dsc$a_pointer = progname;
    prognamedsc.dsc$w_length = strlen(progname);

    /* Start it.  */

    ker$create_job(&sts, &jobport, &prognamedsc, NULL);
    return sts;
}
示例#14
0
文件: main.c 项目: mvjunq/jucilei
int main (int argc, char *argv[]) {

    char cmd[256];
    int ret;

    ret = shell_init() ;

    if (ret < 0) {
        return -1;
    }

    while (printf("$ "), fgets (cmd, 256, stdin) != NULL) {
        ret = create_job (cmd);
        if (IS_SYNTAX_ERROR (ret)) {
            puts ("Syntax Error!");
        }
        else if (IS_CMD_LINE_OK (ret))
            run_fg_job();
    }



    return EXIT_SUCCESS;
}
示例#15
0
void ini_StartApplications ()
{
    pwr_tStatus sts;
    pwr_sAppl *applp;
    pwr_tObjid objid;
#ifdef	OS_ELN
    $DESCRIPTOR(prognamedsc, "");
    $DESCRIPTOR(nulldsc, "");
    $DESCRIPTOR(argdsc, "");
    VARYING_STRING(255) filename;
    VARYING_STRING(41) progname;
    char tmpfilename[255],hostspec[20],*cp;
    PORT jobport;
#endif
#ifdef	OS_VMS
    $DESCRIPTOR(prognamedsc, "");
    $DESCRIPTOR(nulldsc, "");
    $DESCRIPTOR(argdsc, "");
    char spawnbuf [512] = "";
    $DESCRIPTOR (SpawnCommand, "");
    $DESCRIPTOR (SpawnPrcnam, "Appl Start");
    pwr_tUInt32 Flags;
#endif

    /* Find the $Appl objects on this particular node */

    sts = gdh_GetClassList(pwr_eClass_Appl, &objid);
    while (ODD(sts)) {
        if (ODD(gdh_ObjidToPointer(objid, (pwr_tAddress *)&applp))) {

            /* Found an object on this node, load the program */

#ifdef	OS_ELN

            if (strlen(applp->FileName) > 0) {

                /* Check whether we booted from a local disk or not */
                if (ini_LocalBoot()) {

                    /* Local boot */

                    /* Find the filename. Beyond the last ':' */
                    cp = strrchr(applp->FileName,':');
                    if ( cp )
                        *cp++;
                    else
                        cp = applp->FileName;

                    /* Build the application filename. */
                    sprintf(tmpfilename,"%s%s",ini_BootFilesLocation(),cp);

                } else {

                    /* Remote boot */

                    /* Check if application name contains '::'. If not - add hostspec */
                    cp = strstr(applp->FileName,"::");
                    if (!cp ) {
                        ini_GetNodeInfo(NULL, NULL, NULL, hostspec, NULL, NULL);
                        sprintf(tmpfilename,"%s::%s",hostspec,applp->FileName);
                    } else {
                        strcpy(tmpfilename,applp->FileName);
                    }
                }
                errh_Info("Load program '%s'", tmpfilename);

                CSTRING_TO_VARYING(tmpfilename, filename);
                CSTRING_TO_VARYING(applp->ProgramName, progname);

                eln$load_program(&filename, &progname, applp->KernelMode,
                                 applp->StartWithDebug, FALSE, applp->KernelStackSize, 1,
                                 10, applp->JobPriority, applp->ProcessPriority, &sts);
                if (EVEN(sts)) errh_Error("eln$load_program '%s'\n%m", applp->ProgramName, sts);
            }

            if (ODD(sts)) {

                /* Start it */

                errh_Info("Start program '%s'", applp->ProgramName);

                prognamedsc.dsc$a_pointer = applp->ProgramName;
                prognamedsc.dsc$w_length = strlen(applp->ProgramName);

                argdsc.dsc$a_pointer = applp->Arg;
                argdsc.dsc$w_length = strlen (applp->Arg);

                ker$create_job(&sts, &jobport, &prognamedsc, NULL, &nulldsc, &nulldsc, &nulldsc, &argdsc);

                if (EVEN(sts)) errh_Error("ker$create_job '%s'\n%m", applp->ProgramName, sts);
            }


#elif defined(OS_VMS)

            sprintf(spawnbuf, "$ @pwr_exe:rt_ini_appl_start %s \"%s\" %d %d \"%s\"",
                    applp->FileName, applp->ProgramName,
                    applp->StartWithDebug, applp->JobPriority,
                    applp->Arg);
            SpawnCommand.dsc$w_length = strlen(spawnbuf);
            SpawnCommand.dsc$a_pointer = spawnbuf;
            Flags = 1; /* Nowait and Notify */
            errh_Info("Starting %s\nin process %s", applp->FileName, applp->ProgramName);
            sts = lib$spawn(&SpawnCommand, NULL, NULL, &Flags);
            if (EVEN(sts)) errh_Error("lib$spawn '%s'\n%m", spawnbuf, sts);

#elif defined(OS_LYNX) || defined(OS_LINUX)

            errh_Error("NYI. start %s \"%s\" %d %d \"%s\"",
                       applp->FileName, applp->ProgramName,
                       applp->StartWithDebug, applp->JobPriority,
                       applp->Arg);
#endif

        } /* Local appl object */

        sts = gdh_GetNextObject (objid, &objid);
    }
}
示例#16
0
static int				/* O - Command status */
recv_print_job(
    const char    *queue,		/* I - Printer name */
    int           num_defaults,		/* I - Number of default options */
    cups_option_t *defaults)		/* I - Default options */
{
  http_t	*http;			/* HTTP connection */
  int		i;			/* Looping var */
  int		status;			/* Command status */
  int		fd;			/* Temporary file */
  FILE		*fp;			/* File pointer */
  char		filename[1024];		/* Temporary filename */
  ssize_t	bytes;			/* Bytes received */
  size_t	total;			/* Total bytes */
  char		line[256],		/* Line from file/stdin */
		command,		/* Command from line */
		*count,			/* Number of bytes */
		*name;			/* Name of file */
  const char	*job_sheets;		/* Job sheets */
  int		num_data;		/* Number of data files */
  char		control[1024],		/* Control filename */
		data[100][256],		/* Data files */
		temp[100][1024];	/* Temporary files */
  char		user[1024],		/* User name */
		title[1024],		/* Job title */
		docname[1024],		/* Document name */
		dest[256];		/* Printer/class queue */
  int		accepting,		/* printer-is-accepting */
		shared,			/* printer-is-shared */
		num_options;		/* Number of options */
  cups_option_t	*options;		/* Options */
  int		id;			/* Job ID */
  int		docnumber,		/* Current document number */
		doccount;		/* Count of documents */


 /*
  * Connect to the server...
  */

  http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption());
  if (!http)
  {
    syslog(LOG_ERR, "Unable to connect to server: %s", strerror(errno));

    putchar(1);

    return (1);
  }

 /*
  * See if the printer is available...
  */

  num_options = get_printer(http, queue, dest, sizeof(dest), &options,
                            &accepting, &shared, NULL);

  if (num_options < 0 || !accepting || !shared)
  {
    if (dest[0])
      syslog(LOG_INFO, "Rejecting job because \"%s\" is not %s", dest,
             !accepting ? "accepting jobs" : "shared");
    else
      syslog(LOG_ERR, "Unable to get printer information for \"%s\"", queue);

    httpClose(http);

    putchar(1);

    return (1);
  }

  putchar(0);				/* OK so far... */

 /*
  * Read the request...
  */

  status   = 0;
  num_data = 0;
  fd       = -1;

  control[0] = '\0';

  while (smart_gets(line, sizeof(line), stdin) != NULL)
  {
    if (strlen(line) < 2)
    {
      status = 1;
      break;
    }

    command = line[0];
    count   = line + 1;

    for (name = count + 1; *name && !isspace(*name & 255); name ++);
    while (isspace(*name & 255))
      *name++ = '\0';

    switch (command)
    {
      default :
      case 0x01 : /* Abort */
          status = 1;
	  break;

      case 0x02 : /* Receive control file */
          if (strlen(name) < 2)
	  {
	    syslog(LOG_ERR, "Bad control file name \"%s\"", name);
	    putchar(1);
	    status = 1;
	    break;
	  }

          if (control[0])
	  {
	   /*
	    * Append to the existing control file - the LPD spec is
	    * not entirely clear, but at least the OS/2 LPD code sends
	    * multiple control files per connection...
	    */

	    if ((fd = open(control, O_WRONLY)) < 0)
	    {
	      syslog(LOG_ERR,
	             "Unable to append to temporary control file \"%s\" - %s",
        	     control, strerror(errno));
	      putchar(1);
	      status = 1;
	      break;
	    }

	    lseek(fd, 0, SEEK_END);
          }
	  else
	  {
	    if ((fd = cupsTempFd(control, sizeof(control))) < 0)
	    {
	      syslog(LOG_ERR, "Unable to open temporary control file \"%s\" - %s",
        	     control, strerror(errno));
	      putchar(1);
	      status = 1;
	      break;
	    }

	    strlcpy(filename, control, sizeof(filename));
	  }
	  break;

      case 0x03 : /* Receive data file */
          if (strlen(name) < 2)
	  {
	    syslog(LOG_ERR, "Bad data file name \"%s\"", name);
	    putchar(1);
	    status = 1;
	    break;
	  }

          if (num_data >= (int)(sizeof(data) / sizeof(data[0])))
	  {
	   /*
	    * Too many data files...
	    */

	    syslog(LOG_ERR, "Too many data files (%d)", num_data);
	    putchar(1);
	    status = 1;
	    break;
	  }

	  strlcpy(data[num_data], name, sizeof(data[0]));

          if ((fd = cupsTempFd(temp[num_data], sizeof(temp[0]))) < 0)
	  {
	    syslog(LOG_ERR, "Unable to open temporary data file \"%s\" - %s",
        	   temp[num_data], strerror(errno));
	    putchar(1);
	    status = 1;
	    break;
	  }

	  strlcpy(filename, temp[num_data], sizeof(filename));

          num_data ++;
	  break;
    }

    putchar(status);

    if (status)
      break;

   /*
    * Copy the data or control file from the client...
    */

    for (total = (size_t)strtoll(count, NULL, 10); total > 0; total -= (size_t)bytes)
    {
      if (total > sizeof(line))
        bytes = (ssize_t)sizeof(line);
      else
        bytes = (ssize_t)total;

      if ((bytes = (ssize_t)fread(line, 1, (size_t)bytes, stdin)) > 0)
        bytes = write(fd, line, (size_t)bytes);

      if (bytes < 1)
      {
	syslog(LOG_ERR, "Error while reading file - %s",
               strerror(errno));
        status = 1;
	break;
      }
    }

   /*
    * Read trailing nul...
    */

    if (!status)
    {
      if (fread(line, 1, 1, stdin) < 1)
      {
        status = 1;
	syslog(LOG_ERR, "Error while reading trailing nul - %s",
               strerror(errno));
      }
      else if (line[0])
      {
        status = 1;
	syslog(LOG_ERR, "Trailing character after file is not nul (%02X)!",
	       line[0]);
      }
    }

   /*
    * Close the file and send an acknowledgement...
    */

    close(fd);

    putchar(status);

    if (status)
      break;
  }

  if (!status)
  {
   /*
    * Process the control file and print stuff...
    */

    if ((fp = fopen(control, "rb")) == NULL)
      status = 1;
    else
    {
     /*
      * Copy the default options...
      */

      for (i = 0; i < num_defaults; i ++)
	num_options = cupsAddOption(defaults[i].name,
		                    defaults[i].value,
		                    num_options, &options);

     /*
      * Grab the job information...
      */

      title[0]   = '\0';
      user[0]    = '\0';
      docname[0] = '\0';
      doccount   = 0;

      while (smart_gets(line, sizeof(line), fp) != NULL)
      {
       /*
        * Process control lines...
	*/

	switch (line[0])
	{
	  case 'J' : /* Job name */
	      strlcpy(title, line + 1, sizeof(title));
	      break;

          case 'N' : /* Document name */
              strlcpy(docname, line + 1, sizeof(docname));
              break;

	  case 'P' : /* User identification */
	      strlcpy(user, line + 1, sizeof(user));
	      break;

	  case 'L' : /* Print banner page */
	     /*
	      * If a banner was requested and it's not overridden by a
	      * command line option and the destination's default is none
	      * then add the standard banner...
	      */

	      if (cupsGetOption("job-sheets", num_defaults, defaults) == NULL &&
        	  ((job_sheets = cupsGetOption("job-sheets", num_options,
					       options)) == NULL ||
        	   !strcmp(job_sheets, "none,none")))
	      {
		num_options = cupsAddOption("job-sheets", "standard",
		                	    num_options, &options);
	      }
	      break;

	  case 'c' : /* Plot CIF file */
	  case 'd' : /* Print DVI file */
	  case 'f' : /* Print formatted file */
	  case 'g' : /* Plot file */
	  case 'l' : /* Print file leaving control characters (raw) */
	  case 'n' : /* Print ditroff output file */
	  case 'o' : /* Print PostScript output file */
	  case 'p' : /* Print file with 'pr' format (prettyprint) */
	  case 'r' : /* File to print with FORTRAN carriage control */
	  case 't' : /* Print troff output file */
	  case 'v' : /* Print raster file */
	      doccount ++;

	      if (line[0] == 'l' &&
	          !cupsGetOption("document-format", num_options, options))
		num_options = cupsAddOption("raw", "", num_options, &options);

              if (line[0] == 'p')
		num_options = cupsAddOption("prettyprint", "", num_options,
		                	    &options);
              break;
	}

	if (status)
	  break;
      }

     /*
      * Check that we have a username...
      */

      if (!user[0])
      {
	syslog(LOG_WARNING, "No username specified by client! "
		            "Using \"anonymous\"...");
	strlcpy(user, "anonymous", sizeof(user));
      }

     /*
      * Create the job...
      */

      if ((id = create_job(http, dest, title, docname, user, num_options,
                           options)) < 0)
        status = 1;
      else
      {
       /*
	* Then print the job files...
	*/

	rewind(fp);

	docname[0] = '\0';
	docnumber  = 0;

	while (smart_gets(line, sizeof(line), fp) != NULL)
	{
	 /*
          * Process control lines...
	  */

	  switch (line[0])
	  {
	    case 'N' : /* Document name */
		strlcpy(docname, line + 1, sizeof(docname));
		break;

	    case 'c' : /* Plot CIF file */
	    case 'd' : /* Print DVI file */
	    case 'f' : /* Print formatted file */
	    case 'g' : /* Plot file */
	    case 'l' : /* Print file leaving control characters (raw) */
	    case 'n' : /* Print ditroff output file */
	    case 'o' : /* Print PostScript output file */
	    case 'p' : /* Print file with 'pr' format (prettyprint) */
	    case 'r' : /* File to print with FORTRAN carriage control */
	    case 't' : /* Print troff output file */
	    case 'v' : /* Print raster file */
               /*
		* Figure out which file we are printing...
		*/

		for (i = 0; i < num_data; i ++)
	          if (!strcmp(data[i], line + 1))
		    break;

        	if (i >= num_data)
		{
	          status = 1;
		  break;
		}

               /*
		* Send the print file...
		*/

        	docnumber ++;

        	if (print_file(http, id, temp[i], docname, user,
		               cupsGetOption("document-format", num_options,
			                     options),
	                       docnumber == doccount))
                  status = 1;
		else
	          status = 0;

		break;
	  }

	  if (status)
	    break;
	}
      }

      fclose(fp);
    }
  }

  cupsFreeOptions(num_options, options);

  httpClose(http);

 /*
  * Clean up all temporary files and return...
  */

  unlink(control);

  for (i = 0; i < num_data; i ++)
    unlink(temp[i]);

  return (status);
}
示例#17
0
文件: solosh.c 项目: danfyty/solosh
int main(int argc, char* argv[])
{
	char* str, dir[SLSH_MAX_PATH];
	char opt_ver[] = "version", opt_comm[] = "command";
	char shortopts[] = "c:";
	JOB* job = NULL;
	struct sigaction chld;
	struct option longopts[3];
	int opt, is_script = 0;
	char doc[] = "SoloSH 1.0 (beta)\nCopyright (C) 2016 Rodrigo Weigert <*****@*****.**>\n"
	   			 "This program comes WITHOUT ANY WARRANTY, without even the implied\n"
			     "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
				 "See the GNU General Public License for more details.\n\n"
		    	 "This is free software, and you are welcome to redistribute it and/or\n"
				 "modify it under the terms of the GNU General Public License; either\n"
				 "version 3 of the License, or (at your option) any later version.\n\n";

	longopts[0].name = opt_ver;
	longopts[0].has_arg = no_argument;
	longopts[0].flag = NULL;
	longopts[0].val = 1;

	longopts[1].name = opt_comm;
	longopts[1].has_arg = required_argument;
	longopts[1].flag = NULL;
	longopts[1].val = 'c';

	memset(longopts+2, 0, sizeof(struct option)); 
	
	setpgid(0, 0);

	memset(&chld, 0, sizeof(struct sigaction));
	chld.sa_flags |= SA_SIGINFO;
	chld.sa_sigaction = sigchld_handler;
	error(sigaction(SIGCHLD, &chld, NULL) < 0, -1);

    signal (SIGINT, SIG_IGN);
    signal (SIGQUIT, SIG_IGN);
    signal (SIGTSTP, SIG_IGN);
    signal (SIGTTIN, SIG_IGN);
    signal (SIGTTOU, SIG_IGN);

	opt = getopt_long(argc, argv, shortopts, longopts, NULL);
	if (opt == 'c')
	{
		job = create_job(optarg);
		run_job(job);
		job_list(JL_DESTROY);
		return 0;
	}
	if (opt == '?')
		return -1;

	if (opt == 1)
	{
		printf("%s", doc);
		return 0;
	}

	if (argc > 2)
	{
		printf("Too many arguments.\n");
		return -1;
	}
	if (argc == 2)
	{
		int in = open(argv[1], O_RDONLY);
		fatal_error(in < 0, -1);
		close(0);
		fatal_error(dup(in) < 0, -1);
		close(in);
		is_script = 1;
	}

	if (!is_script)
		printf("%s", doc);
	
	while (!exit_flag)
	{
		if (!is_script)
		{
			char *raux = getcwd(dir, SLSH_MAX_PATH*sizeof(char));
            fatal_error (raux == NULL, -1);
			printf("@ %s: ", dir);
		}

		while (str = read_line(), str == NULL)
		{
			if (feof(stdin))
			{
				exit_flag = 1;
				printf("\n");
				break;
			}
			else if (!is_script)
				printf("@ %s: ", dir);
		}
		
		if (!exit_flag)
		{
			job = create_job(str);
			run_job(job);
		}
		free(str);
		str = NULL;
	}

	job_list(JL_DESTROY);
	return 0;
}
示例#18
0
文件: assgn1.c 项目: WarSame/BB4Asst1
// function main ------------------------------------------------- 
int main(int argc,char** argv) {
  int i, j;
  
  // TO DO 
  // check the number of command line arguments, if not 2, terminate
  // the program with a proper error message on the screen.
if (argc != 2){
	perror("You do not have 2 arguments!");
	exit(EXIT_FAILURE);
}

  // check if the single command line argument (argv[1]) has value 3 to 6,
  // if not, treminate the program with a proper error message on the
if (3 < atoi(argv[1]) && atoi(argv[1]) > 6){
	perror("You need 3 to 6 jobs!");
	exit(EXIT_FAILURE);
}
else {
	number_of_jobs = atoi(argv[1]);
}
  // screen.
  // set appropriately number_of_jobs
  // END TO DO 
  
  create_log("assgn1.log");
  
  // TO DO
  // prepare mymask1 -- SIGCHLD and SIGALRM blocked, all other signals free 
  // using sigemptyset(), sigfillset(), sigaddset(), sigdelset() 
sigemptyset(&mymask1);
//sigfillset(&mymask1);
sigaddset(&mymask1, SIGCHLD);
sigaddset(&mymask1, SIGALRM);
  // END TO DO
 
  // TO DO
  // instal mymask1 as the process signal mask using sigrpocmask()
if (sigprocmask(SIG_SETMASK, &mymask1, NULL) == -1){
	perror("Failed to install mymask1.");
	return -1;
}
  // END TO DO 
  
  // TO DO
  // prepare mymask2 -- all signals free 
  // using sigemptyset(), sigfillset(), sigaddset(), sigdelset() 
sigemptyset(&mymask2);

  // END TO DO
  
  // TO DO
  // prepare jobmask -- all signals blocked except SIGUSR2 
  // using sigemptyset(), sigfillset(), sigaddset(), sigdelset() 
if (sigfillset(&jobmask) == -1){
	perror("Failed to fill jobmask.");
	return -1;
}
if (sigdelset(&jobmask, SIGUSR2)){
	perror("Failed to remove SIGUSR2 from jobmask.");
	return -1;
}
  // END TO DO

  // TO DO
  // prepare SIGALRM disposition sa_alarm
  // its handler (sa_handler) is siga_handler()
  // its signal mask (sa_mask) must block all signals
  // its flags (sa_flags) must be set to SA_RESTART 


sa_alarm.sa_handler=siga_handler;
sigemptyset(&sa_alarm.sa_mask);
sa_alarm.sa_flags=SA_RESTART;
  // END TO DO
  
  // TO DO
  // instal SIGALRM disposition using sigaction() 
if (sigaction(SIGALRM, &sa_alarm, NULL) == -1){
	perror("Failed to install SIGALRM disposition.");
	return -1;
}

  // END TO DO
  
  // TO DO
  // prepare SIGCHLD disposition sa_chld
  // its handler (sa_handler) is sigc_handler()
  // its signal mask (sa_mask) must block all signals
  // its flags (sa_flags) must be set to SA_RESTART 
sa_chld.sa_handler=sigc_handler;
sigemptyset(&sa_chld.sa_mask);
sa_chld.sa_flags=SA_RESTART;
  // END TO DO

  // TO DO
  // instal SIGCHLD disposition using sigaction() 
if (sigaction(SIGCHLD, &sa_chld, NULL) == -1){
	perror("Failed to install SIGCHLD disposition.");
	return -1;
}
  // END TO DO

  // TO DO
//Create empty queues
lP = createQueue();
mP = createQueue();
hP = createQueue();
  // END TO DO
  
  // TO DO
  // create a data structure to keep information about jobs - PID, number of runs
  // put all jobs in the high-priority queue
for(i = 0; i < number_of_jobs; i++) {
	pid = create_job(i);
	hP.push(&hP, pid, i, 0);
	//currentPID = pid;
}
  // END TO DO

  // TO DO
  // in a loop
  //    if all queues are empty  
//       record it in the log by Msg("All jobs done\n");
  //       and display it on the screen by msg("All jobs done\n");
  //       and terminate the loop
while(1){
if (hP.isEmpty(&hP) == 1 && mP.isEmpty(&mP) == 1 && lP.isEmpty(&lP) == 1){
	Msg("All jobs done\n");
	msg("All jobs done\n");
	break;
}
//Demote all necessary jobs and put them back in their respective queue

//	hP.display(&hP);
//	mP.display(&mP);
//	lP.display(&lP);

  //    "switch on" the first job from the highest-priority non-empty queue
  //    by sending it the SIGUSR1 signal (using sigsend())
  //    Record it in the log using 
  //        Msg("Switched on high-priority job %d\n",job number);  or
  //        Msg("Switched on medium-priority job %d\n",job number); or
  //        Msg("Switched on low-priority job %d\n",job number); 

if (hP.isEmpty(&hP) == 0){
	currentRuns = hP.peekRuns(&hP);
	currentJob = hP.peekJob(&hP);
	currentPID = hP.peekProcess(&hP);
	Msg("Switched on high-priority job %d\n", currentJob);
	msg("Switched on high-priority job %d\n", currentJob);
	kill(currentPID, SIGUSR1);
}
else if (mP.isEmpty(&mP) == 0){
	currentRuns = mP.peekRuns(&mP);
	currentJob = mP.peekJob(&mP);
	currentPID = mP.peekProcess(&mP);
	Msg("Switched on medium-priority job %d\n", currentJob);
	msg("Switched on medium-priority job %d\n", currentJob);
	kill(currentPID, SIGUSR1);
}
else {
	currentRuns = lP.peekRuns(&lP);
	currentJob = lP.peekJob(&lP);
	currentPID = lP.peekProcess(&lP);
	Msg("Switched on low-priority job %d\n", currentJob);
	msg("Switched on low-priority job %d\n", currentJob);
	kill(currentPID, SIGUSR1);
}
alarm(1);
sigsuspend(&mymask2);
  //    announce it on the screen using corresponding msg();
  //    set alarm for 1 second using alarm()

  //    switch the current signal process mask mymask1 to mymask2 while
  //    going to suspension using sigsuspend()
  //    (thus only SIGCHLD or SIGALRM will wake it up from suspension
  //    SIGCHLD indicates that the job that is currently executing just
  //    terminated, SIGALRM indicates that the time for the job currently
  //    executing is up and it must be "switched off")
}
  // end loop
  // END TO DO
    
  return 0;
}// end function main
示例#19
0
int seamule_easy_main(struct seamule_t *seamule, int argc, char *argv[], seamule_process *process) {
    json_t *jobs = NULL;
    json_t *first_job = NULL;
    json_t *payload = NULL;
    json_t *id = NULL;
    json_t *result = NULL;
    json_error_t error;

    jobs = request_jobs(seamule);
    if (!jobs) {
        fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
        goto error;
    }

    if (!json_is_array(jobs)) {
        fprintf(stderr, "error: root is not an array\n");
        goto error;
    }

    if (json_array_size(jobs) == 0) {
        first_job = create_job(seamule);
    } else {
        first_job = json_array_get(jobs, 0);
    }

    if (!first_job) {
        fprintf(stderr, "error: root is empty\n");
        goto error;
    }

    if (!json_is_object(first_job)) {
        fprintf(stderr, "error: job %d is not an object\n", 1);
        goto error;
    }

    id = json_object_get(first_job, "id");
    if (!json_is_string(id)) {
        fprintf(stderr, "error: job id is not a string\n");
        goto error;
    }

    payload = json_object_get(first_job, "payload");

    result = process(payload);

    if (result) {
        send_result(seamule, json_string_value(id), result);
        json_decref(result);
    }

    json_decref(id);
    json_decref(jobs);
    json_decref(first_job);
    json_decref(payload);

    return 0;

    error:
    if (id)
        json_decref(id);
    if (jobs)
        json_decref(jobs);
    if (first_job)
        json_decref(first_job);
    return 1;
}
示例#20
0
int main(int argc, char *argv[]){
  jlist = create_job_list();

  char *tok;
  TOKENIZER *tokenizer;
  int ispipe, redirect_out_flag, redirect_in_flag, not_exec_cmd, is_bg_flag;

  //read-in buffer
  char data[BUFFER_MAX]; 
  char extra[1]; 

  //linked list to add argument arrays to execvp: 1 for process 1, 2 for piped process
  list_elt *argv2_elt = NULL; 
  list_elt *argv1_elt = NULL;
  message_q = NULL;
  int argv1size = 0;
  int argv2size = 0;
  int status;

  //set shell pgid
  sh_pgid = getpgid(0);

  //register sigaction for SIGCHLD, SIGINT, SIGTSTP
  struct sigaction handler_action;
  sigaction(SIGCHLD, NULL, &handler_action);  //save previous action for SIGCHLD to handler_action

  //change what handler_action does
  handler_action.sa_flags |= SA_SIGINFO;
  handler_action.sa_flags |= SA_RESTART;

  handler_action.sa_sigaction = child_signal_handler;
  sigfillset(&handler_action.sa_mask);

  // sigaction setup
  sigaction(SIGCHLD, &handler_action, NULL);
  sigaction(SIGTSTP, &handler_action, NULL);
  sigaction(SIGINT, &handler_action, NULL);

  // igmore the sigint and sigtstp sigmals
  signal(SIGINT, SIG_IGN);
  //signal(SIGTSTP, SIG_IGN);

  while(1){
    signal(SIGTTOU, SIG_IGN); //igmore sigttou for tcsetpgrp

    if (-1 == tcsetpgrp(STDIN_FILENO, sh_pgid)){
      perror("tcsetpgrp read error");
    }

    if(-1 == tcsetpgrp(STDOUT_FILENO, sh_pgid)){
      perror("tcsetpgrp read error 2");
    }

    signal(SIGTTOU, SIG_DFL); // un-ignmore sigttou

    print_list(message_q); // print the message_q

    while(message_q){
      message_q =  delete(message_q, message_q); //empty the message_q
    }
    write(STDOUT_FILENO, "kinda-sh# ", 10); //prompt

    //initialize all the flags before tokenizing
    argv1size = 0;
    argv2size = 0;
    is_bg_flag = 0;
    ispipe = 0;
    redirect_out_flag = 0;
    redirect_in_flag = 0;  
    int new_std_in=0; // <
    int new_std_out = 0; // >
    char* fname_in;
    char* fname_out;
    int error_flag=0;
    not_exec_cmd = 0;
    fg_pid=0;

    int read_val;
    data[0] = '\0'; // null terminate data array

    read_val = read(0, data, BUFFER_MAX); // read into the data 


    if(data[0] != '\n'){
      //check if there is buffer overflow
      if((read_val == BUFFER_MAX) && (data[BUFFER_MAX - 1] != '\n')){ 

        while(1){
          argv2_elt = NULL;
          argv1_elt = NULL;
          read(0, extra, 1); // read 1 char at a time from the input stream until its empty (new line)
          if(extra[0] == '\n'){ //read in until the "return(\n) key is hit (similar to flush the std_in)
            break;
          }
        }
      }
      //error handling for inappropriate read size
      if(read_val < 0){ 
        perror("Read"); //check for read error
      } 
      if(read_val == 0){
        kill(0, SIGKILL);
      }

      data[read_val-1] = '\0'; //null terminate dat
      tokenizer = init_tokenizer(data); //create tokenizer on data

      // start tokenizer loop
      while((tok = get_next_token(tokenizer)) != NULL){

        if(is_bg_flag){
          printf("& should be at the end of the command \n");
          error_flag=1;
          break;
        }

        if( (*tok != '|') && (*tok != '&') && (*tok != '<') &&(*tok !=  '>') && (*tok != '\0')){ //check for token

          if(!ispipe){

            if(redirect_out_flag || redirect_in_flag){
              printf("invalid argument between redirection and pipe\n"); //cat < infile something | wc
              error_flag=1;
              break;
            }
            argv1_elt = add(argv1_elt, tok); // add tok to  arv1
            argv1size++;
          }
          else{ // after pipe - second process
            argv2size++;
            argv2_elt = add(argv2_elt, tok);
          }
          //if jobs command called
          if(str_equals(tok, "jobs")){
            print_job_list(jlist);
            not_exec_cmd = 1;
          }

          // if fg command called
          if(str_equals(tok, "fg")){
            job* new_bg_jb;
            char* num;
            num = get_next_token(tokenizer);
            int num_int = -1;
            not_exec_cmd = 1;
            int list_len;
            //if number argument is not specified, take the most recent background job
            if(num == NULL){
              new_bg_jb = get_ith_job(jlist, 1);
              if(new_bg_jb == NULL){
                printf("fg error: no job in job queue\n");
                break;
              }
            }
            //take the num'th background job
            else{
              num_int= my_atoi(num); // run atoi on input number (ie: fg 2)
              //reverse the number into the correct job order
              list_len = listlength(jlist);
              num_int = num_int - list_len -1;

              if(num_int < 0){
                num_int = num_int * (-1);
              }
              new_bg_jb = get_ith_job(jlist, num_int); //get num_int job from the job list

              if(new_bg_jb == NULL){
                printf("fg error: no [%s] job\n", num);
                free(num);
                break;
              } 
            }
            //take the foreground job pid as the chosen bg pid
            fg_pid= new_bg_jb->pgid;
            message_q = add(message_q, "\n"); // add restarting prompt to message_q
            message_q = add(message_q, new_bg_jb->command);
            message_q = add(message_q, "Restarting: ");

            print_list(message_q);
            while(message_q){
              message_q =  delete(message_q, message_q); //empty the message_q
            }

            if(tcsetpgrp(STDIN_FILENO, fg_pid) == -1){
              perror("tcsetpgrp error");
            }

            //relay SIGCONT to the job, and mask it from all signals but SIGCHLD
            killpg(fg_pid, SIGCONT);

            sigset_t cont_mask;
            sigfillset(&cont_mask);
            sigdelset(&cont_mask, SIGCHLD);

            //now the shell should wait for the new foregrounded job to be finished
            while(fg_pid){
              sigsuspend(&cont_mask);
            }
          }
          //take the specific background job to restart. If already running, do nothing.
          if(str_equals(tok, "bg")){
            job* new_bg_jb;
            not_exec_cmd = 1;
            char* num;
            int num_int=-1;
            num = get_next_token(tokenizer);

            // if num is not specified, get the most recent background job (to restart it)
            if(num == NULL){
              new_bg_jb = get_ith_job(jlist, 1);
              if(new_bg_jb == NULL){
                printf("bg error: no job in job queue\n");
                break;
              }
            }
            else{
              num_int= my_atoi(num); // run atoi for bg 
              //set up num_int to pass
              int list_len;
              list_len = listlength(jlist);
              num_int = num_int - list_len -1;
              if(num_int < 0){
                num_int = num_int * (-1);
              }
              new_bg_jb = get_ith_job(jlist, num_int); // get ith job from job_list

              if(new_bg_jb == NULL){
                printf("bg error: no [%s] job\n", num);
                free(num);
                break;
              }
            }

            if(!job_stopped(new_bg_jb)){
              //   tcsetpgrp(STDIN_FILENO, 0);
              printf("bg error: job is already running in the background\n");
              break;
            }

            killpg(new_bg_jb->pgid, SIGCONT);
            tcsetpgrp(STDIN_FILENO, 0);
          }
        }
        else if(*tok=='>'){ // if redirect out token

          if(redirect_out_flag){
            error_flag=1;
            printf("multiple stdout redirection is invalid\n"); //printf?
            break;
          }
          else{
            fname_out = get_next_token(tokenizer); // get hte next token
            new_std_out = open(fname_out, O_WRONLY| O_TRUNC | O_CREAT, 0644); // open file
            if(new_std_out == -1){
              perror("stdout Redir Error");
            }
            redirect_out_flag=1;
          }
        }
        else if(*tok=='<'){ //if redirect in token

          if(ispipe){
            printf("invalid stdin redirection after pipe\n");
            error_flag=1;
            break;
          }
          else if(redirect_in_flag){
            printf("multiple stdin redirection is invalid\n");
            error_flag=1;
            break;
          }            
          else{
            fname_in = get_next_token(tokenizer); // get next token
            new_std_in = open(fname_in, O_RDONLY); // open the file 
            if(new_std_in == -1){
              perror("stdin Redir Error");
            }
          }
        }
        else if(*tok=='|'){ //if pipe token

          if(ispipe){ // cant have more than 1 pipe (didnt do the extra credit)
            printf("invalid multiple pipes\n");
            error_flag=1;
            break;
          }
          else if(redirect_out_flag){
            printf("invalid pipe after stdout redirection\n");
            error_flag=1;
            break;
          }
          ispipe=1; //set a pipe flag
        }
        else if(*tok == '&'){ // if background command
          is_bg_flag = 1;
        }
      }

      if(is_bg_flag){
        data[read_val-2]= '\0'; // delete the '&' from the data array
      }

      argv1size++;
      argv2size++;

      char *argv1[argv1size];
      char *argv2[argv2size];

      if(error_flag || not_exec_cmd){ //if not elecutable command (jobs, fg, bg...) or error flag (bad command)
        while( argv1_elt ){
          argv1_elt = delete(argv1_elt, argv1_elt); //empty the linked list argv1_elt
        }
        while( argv2_elt ){
          argv2_elt = delete(argv2_elt, argv2_elt); //empty the linked list argv2_elt
        }
        continue;
      }

      //set up argv1 array
      list_elt *cursor = argv1_elt;
      list_elt *last;
      int tempIndex=0;
      //last pointer to the last element of argv1_elt linked list
      while(cursor != NULL){
        last = cursor;
        cursor = cursor->next;
      }
      //move all values from argv1_elt into argv1 array.
      while(last != NULL){ 
        argv1[tempIndex]=last->item;
        last = last->prev;
        tempIndex++;
      }
      argv1[argv1size-1] = NULL;

      //set up argv2 array if there's a pipe
      if(ispipe){
        cursor = argv2_elt;
        tempIndex=0;

        //last pointer to the last element of argv2_elt linked list
        while(cursor != NULL){
          last = cursor;
          cursor = cursor->next;
        }
        //move all values from argv2_elt into argv2 array.
        while(last != NULL){ 
          argv2[tempIndex]=last->item; //put input after the pipe into an array argv2
          last = last->prev;
          tempIndex++;
        }
        argv2[argv2size-1] = NULL;
      }
      free_tokenizer( tokenizer ); 

      // tokenizer update done.

      if((pid=fork()) < 0){
        perror("fork1");
      }

      //process & job stuff
      job* jb;
      jb = create_job(); // create corresponding job
      subjob* sj;
      sj = create_subjob(); // create corresponding subjob
      set_command(data, jb);

      if(pid==0){

        if(setpgid(0,0)==-1){
          perror("setpgid error");
        }
        sj->pid = getpid(); // get subjobs pid
        jb->pgid = getpgid(pid);//pid=0
      }
      else{

        if(setpgid(pid, pid)==-1){
          perror("setpgid error");
        }
        // set correct job and subjob pid vals
        sj->pid = pid;
        jb->pgid = pid;
      }

      set_first_subjob(sj, jb); // link subjob to job
      add_new_job(jb, jlist); // add the job to the job_list jlist

      if(pid==0){
        signal(SIGINT, SIG_DFL);
        signal(SIGTSTP, SIG_DFL);

        if(setpgid(0,0)==-1){
          perror("setpgid error");
        }

        if(new_std_out != 0){
          // if redirect out command, dup accordingly
          if(dup2(new_std_out, STDOUT_FILENO) == -1){ //dup2 for > (out)
            perror("stdout dup2");
            _exit(0);
          }
          free(fname_out);
        }

        if(new_std_in != 0){
          // if redirect in command, dup accordingly
          if(dup2(new_std_in, STDIN_FILENO) == -1){ //dup2 for < (in)
            perror("stdin dup2");
            _exit(0);
          }
          free(fname_in);
        }

        if(ispipe){ // if pipe command called
          int filedes[2];

          if(pipe(filedes)){//pipe
            perror("pipe error");
          }
          scnd_pid = fork();

          if(scnd_pid < 0){ //print error if the fork failed
            perror("Fork");
            exit(-1);
          }
          //create a subjob, set its pid for both child and parent
          subjob* sj2;
          sj2 = create_subjob();

          if(scnd_pid==0){
            sj2->pid = getpid(); 
          }
          else{
            sj2->pid = scnd_pid;
          }

          jb->pgid = getpgid(scnd_pid);

          //add to the job group as the first (most recent) process.
          set_first_subjob(sj2, jb);
          set_next_subjob(sj2, sj);
          pipe_pid=sj2->pid;

          if(scnd_pid==0){ // process that writes to pipe (program 1) grand child

            if(close(filedes[0]) == -1){ // close STDIN part of pipe
              perror("close");
            }

            if(dup2(filedes[1], STDOUT_FILENO) == -1){ // dip for STDOUT
              perror("pipe dup2 #1");
            }
            status =  execvp(argv1[0], argv1); // execute

            if(status == -1){  
              perror("execvp program1");
              exit(-1);
            }
            killpg(0, SIGKILL);
            _exit(0); // exit the child
          }
          else{ //program 2; (first fork) process that reads from pipe
            sigset_t sigmask;
            sigfillset(&sigmask);
            sigdelset(&sigmask, SIGCHLD);

            while(pipe_pid){
              sigsuspend(&sigmask);
            }

            if(close(filedes[1]) == -1){ // close STDOUT part of pipe
              perror("close");
            }

            if(dup2(filedes[0], STDIN_FILENO) == -1){ // dup for the STDIN
              perror("dup2 (pipe #2)");
            }

            status = execvp(argv2[0], argv2); // execute the second part of pipe

            if(status == -1){  
              perror("execvp program2");
            }
            killpg(0, SIGKILL);
            _exit(0);
          }
        }
        else{ // if not pipe, pid.
          status = execvp(argv1[0], argv1); 

          if(status == -1){  
            perror("execvp");
          }
          _exit(0);
        }
      } 
      else{ //kinda-sh
        if(setpgid(pid, pid) ==-1){
          perror("setpgid pid");
        }

        if(is_bg_flag){ //if background command, prompt with running
          printf("Running: %s\n", data);
        }

        if(!is_bg_flag){
          fg_pid= pid; // if not bacground command, set the fg_pid to be the first fork pid val
          tcsetpgrp(STDIN_FILENO, pid);
        }

        sigset_t sigmask0;
        sigfillset(&sigmask0);
        sigdelset(&sigmask0, SIGCHLD);

        //suspend only if it's not bg process  
        while(fg_pid!=0){
          sigsuspend(&sigmask0);
        }
        if(new_std_in != 0){
          close(new_std_in); //close stdin if used
        }
        if(new_std_out != 0){
          close(new_std_out); //close stdout if used
        }

      }
      while(argv1_elt){
        argv1_elt = delete(argv1_elt, argv1_elt); //empty the linked list argv1_elt
      }
      while(argv2_elt){
        argv2_elt = delete(argv2_elt, argv2_elt); //empty the linked list argv2_elt
      }
    } //if data[0]!=\n
  }//while end

  return 0;
}
示例#21
0
void blur_effect::init(resource_hub& resources) {
    auto render_manager = resources.get<renderer>("renderer");


	downscale_shader = new shader();
	downscale_shader->load_source("data/Shader/GaussianDownscale.vs", shader_type::vertex);
	downscale_shader->load_source("data/Shader/GaussianDownscale.fs", shader_type::fragment);
	downscale_shader->compile();
	downscale_shader->bind();
	downscale_shader->set_int("source_texture", 0);
	downscale_shader->unbind();

	upscale_shader = new shader();
	upscale_shader->load_source("data/Shader/GaussianUpscale.vs", shader_type::vertex);
	upscale_shader->load_source("data/Shader/GaussianUpscale.fs", shader_type::fragment);
	upscale_shader->compile();
	upscale_shader->bind();
	upscale_shader->set_int("source_texture", 0);
	upscale_shader->unbind();

	sprite_shader = resources.get<shader>("sprite-shader");

	for (uint32_t i = 0; i < fbos.size(); ++i) {
		fbos[i] = render_manager->create_render_target(2048 / pow(2, i), 1024 / pow(2, i));
		fbos[i]->clear_before_render = true;
	}

    verticies = std::make_unique<vbo<vec2>>(vbo<vec2>());
    verticies->add(vec2(1, -1));
    verticies->add(vec2(-1, 1));
    verticies->add(vec2(-1, -1));
    verticies->add(vec2(1, -1));
    verticies->add(vec2(1, 1));
    verticies->add(vec2(-1, 1));
    verticies->upload();

    uvs = std::make_unique<vbo<vec2>>(vbo<vec2>());
    uvs->add(vec2(1, 0));
    uvs->add(vec2(0, 1));
    uvs->add(vec2(0, 0));
    uvs->add(vec2(1, 0));
    uvs->add(vec2(1, 1));
    uvs->add(vec2(0, 1));
    uvs->upload();


	// downscale jobs
	for (uint32_t i = 0; i < fbos.size() - 1; ++i) {
		downscale_jobs[i] = render_manager->create_job();
		downscale_jobs[i]->blending_mode = render_blending_mode::add;
		downscale_jobs[i]->attach_vbo(verticies.get(), render_job::slot0);
		downscale_jobs[i]->attach_vbo(uvs.get(), render_job::slot1);
		downscale_jobs[i]->render_target = fbos[i + 1];
		downscale_jobs[i]->attach_texture(fbos[i]->get_texture(), 0);
		downscale_jobs[i]->shader = downscale_shader;
		downscale_jobs[i]->z = 20 + i;
		downscale_jobs[i]->bind_var(shader_variable_binding(&fbos[i + 1]->width, downscale_shader->get_var("w")));
		downscale_jobs[i]->bind_var(shader_variable_binding(&fbos[i + 1]->height, downscale_shader->get_var("h")));
		downscale_jobs[i]->upload();
	}

	// upscale jobs
	for (uint32_t i = 0; i < fbos.size() - 1; ++i) {
		upscale_jobs[i] = render_manager->create_job();
		upscale_jobs[i]->blending_mode = render_blending_mode::add;
		upscale_jobs[i]->attach_vbo(verticies.get(), render_job::slot0);
		upscale_jobs[i]->attach_vbo(uvs.get(), render_job::slot1);
		upscale_jobs[i]->render_target = fbos[5 - (i + 1)];
		upscale_jobs[i]->attach_texture(fbos[5 - i]->get_texture(), 0);
		upscale_jobs[i]->shader = upscale_shader;
		upscale_jobs[i]->z = 25 + i;
		upscale_jobs[i]->bind_var(shader_variable_binding(&fbos[5 - i]->width, upscale_shader->get_var("w")));
		upscale_jobs[i]->bind_var(shader_variable_binding(&fbos[5 - i]->height, upscale_shader->get_var("h")));
		upscale_jobs[i]->upload();
	}

	finish_job = render_manager->create_job();
	finish_job->blending_mode = render_blending_mode::add;
	finish_job->attach_vbo(verticies.get(), render_job::slot0);
	finish_job->attach_vbo(uvs.get(), render_job::slot1);
	finish_job->attach_texture(fbos[0]->get_texture(), 0);
	finish_job->shader = sprite_shader;
	finish_job->z = 31;
	finish_job->bind_var(shader_variable_binding(&mat4::id, sprite_shader->get_var("view_matrix")));
	finish_job->upload();
}