示例#1
0
/* Allocate memory for a new pipeline. */
pipeline_t *new_pipeline (void)
{
    pipeline_t *pipeline;
    int i, j;

    pipeline = malloc (1 * sizeof(pipeline_t));
    sysfail (!pipeline, NULL);


    /* Allocate a pipeline structure. */
    pipeline->command = malloc ((MAX_COMMANDS + 1) * sizeof(char **));
    if (!pipeline->command)
    {
        sysdebug (1);
        free (pipeline);
        return NULL;
    }

    /* Allocate memory for commands. */
    for (i = 0; i < MAX_COMMANDS + 1; i++)
    {
        pipeline->command[i] = malloc ((MAX_ARGUMENTS + 1) * sizeof (char *));
        if (!pipeline->command[i])
        {
            sysdebug(1);
            for (j = 0; j < i; j++)
                free (pipeline->command[j]);
            free(pipeline->command);
            free (pipeline);
            return NULL;
        }
    }

    pipeline->ground = FOREGROUND;
    pipeline->file_in[0] = '\0';
    pipeline->file_out[0] = '\0';

    return pipeline;

}
示例#2
0
void * worker_thread (void *arg)
{
  int nbytes, new_fd;
  char buffer [BUFFER_SIZE];
  struct targ_t *targ;
  int pid, status, rsc;
  char *args[MAX_ARGS];

  targ = (struct targ_t *) arg;
  
  new_fd = targ->fd;
  
  do
    {

      nbytes = read (new_fd, buffer, BUFFER_SIZE-1);
      
      buffer[nbytes]=0; 
      
      if (nbytes>0)
	{

	  /* Create a subprocess to execute external program (command). */
	  pid = fork();
	  sysfatal (pid<0);

	  if (pid>0) 		/* Original process (worker thread). */
	    {
	      wait (&status);
	      if (!WIFEXITED(status))
		sysdebug (1);
	      else
		printf ("Requested command executed with status %d\n", WEXITSTATUS(status));
	    }
	  else			/* Subprocess. */
	    {


	      parse_args (buffer, args);	      
	      
	      /* Restrict path to local directory (security). */
	      /*printf("%s\n", args[0]);*/ /*args[0] is just p(h)i*/
	      args [0] = strtok (args[0], "./");
	      printf ("Trying [%s]\n", args[0]);
	      rsc = setenv ("PATH", "./", 1); /*  */
	      sysfatal (rsc);

	      /* Redirect standard output to socket. */
	      close (1);
	      dup (new_fd);
	      close (new_fd);
	
	      /* Execute command. */
	      rsc = execvp (args[0], args);
	      printf ("%s: %s\r\n", args[0], strerror(errno));
	      sysfatal (rsc<0);
	    }

	}
    }
  while (nbytes>0);		/* If client disconnects, we read returns 0. */

  pthread_exit (NULL);

  return NULL;
}