예제 #1
0
파일: io.cpp 프로젝트: NewXX/fish-shell
io_buffer_t *io_buffer_t::create(bool is_input)
{
    bool success = true;
    io_buffer_t *buffer_redirect = new io_buffer_t(is_input ? 0 : 1, is_input);

    if (exec_pipe(buffer_redirect->pipe_fd) == -1)
    {
        debug(1, PIPE_ERROR);
        wperror(L"pipe");
        success = false;
    }
    else if (fcntl(buffer_redirect->pipe_fd[0],
                   F_SETFL,
                   O_NONBLOCK))
    {
        debug(1, PIPE_ERROR);
        wperror(L"fcntl");
        success = false;
    }

    if (! success)
    {
        delete buffer_redirect;
        buffer_redirect = NULL;
    }

    return buffer_redirect;
}
예제 #2
0
파일: crypto.c 프로젝트: Cloudxtreme/epic5
static char *	encrypt_by_prog (const unsigned char *str, size_t *len, Crypt *key)
{
        char    *ret = NULL, *input;
        char *  args[3];
        int     iplen;

        args[0] = malloc_strdup(key->prog);
        args[1] = malloc_strdup("encrypt");
        args[2] = NULL;
        input = malloc_strdup2(key->key, "\n");

        iplen = strlen(input);
        new_realloc((void**)&input, *len + iplen);
        memmove(input + iplen, str, *len);

        *len += iplen;
        ret = exec_pipe(key->prog, input, len, args);

        new_free(&args[0]);
        new_free(&args[1]);
        new_free((char**)&input);

        new_realloc((void**)&ret, 1+*len);
        ret[*len] = 0;
        return ret;
}
예제 #3
0
파일: io.cpp 프로젝트: Aulos/fish-shell
io_buffer_t *io_buffer_t::create(int fd)
{
    bool success = true;
    assert(fd >= 0);
    io_buffer_t *buffer_redirect = new io_buffer_t(fd);

    if (exec_pipe(buffer_redirect->pipe_fd) == -1)
    {
        debug(1, PIPE_ERROR);
        wperror(L"pipe");
        success = false;
    }
    else if (make_fd_nonblocking(buffer_redirect->pipe_fd[0]) != 0)
    {
        debug(1, PIPE_ERROR);
        wperror(L"fcntl");
        success = false;
    }

    if (! success)
    {
        delete buffer_redirect;
        buffer_redirect = NULL;
    }
    else
    {
        //fprintf(stderr, "Created pipes {%d, %d} for %p\n", buffer_redirect->pipe_fd[0], buffer_redirect->pipe_fd[1], buffer_redirect);
    }

    return buffer_redirect;
}
예제 #4
0
파일: io.cpp 프로젝트: JanKanis/fish-shell
io_data_t *io_buffer_create(bool is_input)
{
    bool success = true;
    io_data_t *buffer_redirect = new io_data_t;
    buffer_redirect->out_buffer_create();
    buffer_redirect->io_mode = IO_BUFFER;
    buffer_redirect->is_input = is_input ? true : false;
    buffer_redirect->fd=is_input?0:1;

    if (exec_pipe(buffer_redirect->param1.pipe_fd) == -1)
    {
        debug(1, PIPE_ERROR);
        wperror(L"pipe");
        success = false;
    }
    else if (fcntl(buffer_redirect->param1.pipe_fd[0],
                   F_SETFL,
                   O_NONBLOCK))
    {
        debug(1, PIPE_ERROR);
        wperror(L"fcntl");
        success = false;
    }

    if (! success)
    {
        delete buffer_redirect;
        buffer_redirect = NULL;
    }

    return buffer_redirect;
}
예제 #5
0
파일: pipe.c 프로젝트: TH3Mjuss/QuadriSH
int	my_pipe(char **cmd, char **env)
{
    int	pid;
    int	ret;

    ret = 0;
    if ((pid = fork()) < 0)
        return (1);
    if (pid == 0)
    {
        exec_pipe(cmd, env);
        exit(0);
    }
    else
        wait(&ret);
    return (ret);
}
예제 #6
0
int	pipe_parsing(char *str)
{
  char	**tab_pipe;
  int	ret;
  int	tab_len;

  if (!valid_str(str) || !last_verif(str))
    return (0);
  if (in_str(str, token_val("|")) &&
      (tab_pipe = str_to_wordtab(str, token_val("|"))))
    {
      tab_len = count_tab(tab_pipe);
      ret = exec_pipe(tab_pipe, tab_len);
      free(tab_pipe);
    }
  else
    ret = parse_command_redir(str);
  return (ret);
}
예제 #7
0
int execute_and_create_process(struct subprocess* process, struct inotify_event* event, char *command) { //Execute command using wrapper function.
	process->start_time=(char*)malloc(sizeof(char)*9);
	strcpy(process->start_time,get_time_string());
	int pid=exec_pipe(command,0);
	if (pid==-1) {
		return -1;
	}
	process->pid=pid;
	process->retries=0;
	process->command=(char *)malloc(sizeof(char)*strlen(command));
	process->event=event;
	process->prev=NULL;
	process->next=NULL;
	strcpy(process->command,command);
	process->path=(char *)malloc(sizeof(char)*(strlen(global_wd_list[event->wd]->path)+strlen(event->name)+2));
	sprintf(process->path,"%s/%s",global_wd_list[event->wd]->path,event->name);
	add_list_element(process);
	return pid;
}
예제 #8
0
int	exec_course_branch_select(t_node *root, t_global *global)
{
  int	status;

  if (root->id == PIPE)
    {
      if ((status = exec_pipe(root, global)) >= EXIT_FAILURE)
	return (status);
    }
  else if (root->id == CMD)
    {
      if ((status = exec_command(root, global->env)) >= EXIT_FAILURE)
	return (status);
    }
  else
    {
      if ((status = exec_redirection(root, global, root->id)) >= EXIT_FAILURE)
	return (status);
    }
  return (EXIT_SUCCESS);
}
예제 #9
0
파일: ft_exec.c 프로젝트: YanisSOTO/42sh
void	ft_launch_exec(char *command, char ***env, int *execve_flag)
{
	char	**path;
	char	**cmd_arg;

	if (ft_strsrch(command, '|') != -1)
		exec_pipe(env, command, execve_flag);
	else
	{
		cmd_arg = get_clean_arg(command, *env);
		if (((path = ft_path(env, cmd_arg[0])) == NULL)
				&& ft_strcmp(command, "exit") != 0)
			ft_putendl("Set a good path or you will take expensive.");
		if ((ft_rd(command, env, execve_flag) == 1)
				&& (builtin(env, cmd_arg) == 0))
		{
			ft_execute_cmd(path, cmd_arg, *env, execve_flag);
			if (path)
				ft_tabfree(path);
		}
	}
}
예제 #10
0
파일: io.cpp 프로젝트: haarts/fish-shell
io_buffer_t *io_buffer_t::create(int fd, const io_chain_t &conflicts) {
    bool success = true;
    assert(fd >= 0);
    io_buffer_t *buffer_redirect = new io_buffer_t(fd);

    if (exec_pipe(buffer_redirect->pipe_fd) == -1) {
        debug(1, PIPE_ERROR);
        wperror(L"pipe");
        success = false;
    } else if (!buffer_redirect->avoid_conflicts_with_io_chain(conflicts)) {
        // The above call closes the fds on error.
        success = false;
    } else if (make_fd_nonblocking(buffer_redirect->pipe_fd[0]) != 0) {
        debug(1, PIPE_ERROR);
        wperror(L"fcntl");
        success = false;
    }

    if (!success) {
        delete buffer_redirect;
        buffer_redirect = NULL;
    }
    return buffer_redirect;
}
예제 #11
0
io_buffer_t *io_buffer_t::create(bool is_input, int fd)
{
    bool success = true;
    if (fd == -1)
    {
        fd = is_input ? 0 : 1;
    }
    io_buffer_t *buffer_redirect = new io_buffer_t(fd, is_input);

    if (exec_pipe(buffer_redirect->pipe_fd) == -1)
    {
        debug(1, PIPE_ERROR);
        wperror(L"pipe");
        success = false;
    }
    else if (fcntl(buffer_redirect->pipe_fd[0],
                   F_SETFL,
                   O_NONBLOCK))
    {
        debug(1, PIPE_ERROR);
        wperror(L"fcntl");
        success = false;
    }

    if (! success)
    {
        delete buffer_redirect;
        buffer_redirect = NULL;
    }
    else
    {
        //fprintf(stderr, "Created pipes {%d, %d} for %p\n", buffer_redirect->pipe_fd[0], buffer_redirect->pipe_fd[1], buffer_redirect);
    }

    return buffer_redirect;
}
예제 #12
0
파일: io.cpp 프로젝트: elnappo/fish-shell
shared_ptr<io_buffer_t> io_buffer_t::create(int fd, const io_chain_t &conflicts,
                                            size_t buffer_limit) {
    bool success = true;
    assert(fd >= 0);
    shared_ptr<io_buffer_t> buffer_redirect(new io_buffer_t(fd, buffer_limit));

    if (exec_pipe(buffer_redirect->pipe_fd) == -1) {
        debug(1, PIPE_ERROR);
        wperror(L"pipe");
        success = false;
    } else if (!buffer_redirect->avoid_conflicts_with_io_chain(conflicts)) {
        // The above call closes the fds on error.
        success = false;
    } else if (make_fd_nonblocking(buffer_redirect->pipe_fd[0]) != 0) {
        debug(1, PIPE_ERROR);
        wperror(L"fcntl");
        success = false;
    }

    if (!success) {
        buffer_redirect.reset();
    }
    return buffer_redirect;
}
예제 #13
0
int main(int argc,char *argv[]) {
	fd_count=0;
	lgfile=fopen("logfile.txt","w");

	/* Locking File Config */
	file_lock.l_type   = F_WRLCK;  /* F_RDLCK, F_WRLCK, F_UNLCK    */
	file_lock.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
	file_lock.l_start  = 0;        /* Offset from l_whence         */
	file_lock.l_len    = 0;        /* length, 0 = to EOF           */
	file_lock.l_pid    = getpid(); /* our PID */
	/*Locking File Config */

	strcpy(home_folder,argv[2]);
	strcpy(address,argv[3]);
	strcpy(dest_folder,argv[4]);
	int fd=fd_update(home_folder,-1);

	/* Initalizing linked-list head */
	pid_list.starting=NULL;
	pid_list.last=NULL;
	/*Initializing linked list head */

	/* Setting signal. */
	signal(SIGINT,sigint_handler);
	signal(SIGALRM,timeout);
	/* Setting signal. */

	struct reading_info input;
	input.fd=fd;
	alarm(atoi(argv[1]));
	event_occurred_count=0;
	subprocess_count=0;
	/*Creating thread for inotify. */

	int retvalue;
	if ((retvalue=pthread_create(&inotify_thread,NULL,&wait_for_events,&input))) {
		printf("Thread creation failure. Code: %d\n",retvalue);
	}
	/*Initializing thread-lock variable*/
	if ((pthread_mutex_init(&inotify_event_lock,NULL))) {
		printf("Lock initialization error. Fatal.\n:");
		exit(EXIT_FAILURE);
	}
	/*Initializing thread-lock variable*/
	int status1,i;
	char com[80];
	if (test_if_dir_exists(home_folder)!=0) {
		printf("Making dir...\n");
		sprintf(com,"mkdir %s",home_folder);
		exec_pipe(com,0);
		waitpid(-1,&status1,0);
	}

	/* An initial rsync to sync the two folders */
	sprintf(com,"rsync -azsre ssh --delete \"%s/\" \"%s:%s\"",home_folder,address,dest_folder);
	int sleeptime_initial=5;
	char *temp=(char *)malloc(sizeof(char)*(strlen(com)+3));
	strcpy(temp,com);
	int exit_status=exec_pipe(com,0);
	waitpid(exit_status,&status1,0);
	while (WEXITSTATUS(status1)!=0) {
		strcpy(com,temp);
		exit_status=exec_pipe(com,sleeptime_initial);
		waitpid(exit_status,&status1,0);
		if (sleeptime_initial<1280) {sleeptime_initial*=2;}
	}
	/* An initial rsync to sync the two folders */

	while(1) {
		if (event_occurred_count!=0 && subprocess_count<MAX_EVENT_STACK_SIZE) {	 
			pthread_mutex_lock(&inotify_event_lock);
			int i=0;
			while (i<event_occurred_count) {
				read_event_shell(event_stack[i],fd);
				event_stack[i]=NULL;
				i+=1;
			}
			event_occurred_count=0;
			pthread_mutex_unlock(&inotify_event_lock);
		}
		for (i=0;i<2;i++) {
			poll_pids();
			sleep(1);
		}
	}
	destroy_all();
	fclose(lgfile);
	return 0;
}
예제 #14
0
bool interface(char *line)
{
    
    // Bad practices ftw
    char infile[CSTRSIZE];
    char outfile[CSTRSIZE];
    bool continueExecute = false;
    char *cmd1[CMDSIZE];
    char *cmd2[CMDSIZE];
    int i;
    int k;
    cmd1[0] = NULL;
    cmd2[0] = NULL;
    infile[0] = '\0';
    outfile[0] = '\0';
    
    i = parse_command(line, cmd1, cmd2, infile, outfile);
    if(i == 0)
    {
        continueExecute = true;
    }
    switch(i)
    {
        case 1:
            exec_cmd(cmd1);
            break;
        case 2:
            exec_cmd_in(cmd1, infile);
            break;
        case 3:
            exec_cmd_opt_in_append(cmd1, infile, outfile);
            break;
        case 4:
            exec_cmd_opt_in_write(cmd1, infile, outfile);
            break;
        case 5:
            exec_pipe(cmd1, cmd2);
            break;
        case 6:
            exec_pipe_in(cmd1, cmd2,infile);
            break;
        case 7:
            exec_pipe_opt_in_append(cmd1, cmd2,infile,outfile);
            break;
        case 8:
            exec_pipe_opt_in_write(cmd1, cmd2,infile,outfile);
            break;
        default:
            break;
    }
    
    if (i > 9)
    {
        k = 0;
        while (cmd1[k] != NULL)
        {
            printf("cmd1[%d] = %s\n", k, cmd1[k]);
            k++;
        };
        k = 0;
        while (cmd2[k] != NULL)
        {
            printf("cmd2[%d] = %s\n", k, cmd2[k]);
            k++;
        };
        if (strlen(infile))
        {
            printf("input redirection file name: %s\n", infile);
        }
        if (strlen(outfile))
        {
            printf("output redirection file name: %s\n", outfile);
        }
    }
    printf("return code is %d\n", i);
    
    return continueExecute;
}
예제 #15
0
파일: exec.c 프로젝트: CodeMonk/fish
void exec( job_t *j )
{
	process_t *p;
	pid_t pid;
	int mypipe[2];
	sigset_t chldset; 
	int skip_fork;
	
	io_data_t pipe_read, pipe_write;
	io_data_t *tmp;

	io_data_t *io_buffer =0;

	/*
	  Set to 1 if something goes wrong while exec:ing the job, in
	  which case the cleanup code will kick in.
	*/
	int exec_error=0;

	int needs_keepalive = 0;
	process_t keepalive;
	

	CHECK( j, );
	CHECK_BLOCK();
	
	if( no_exec )
		return;
	
	sigemptyset( &chldset );
	sigaddset( &chldset, SIGCHLD );
	
	debug( 4, L"Exec job '%ls' with id %d", j->command, j->job_id );	
	
	if( block_io )
	{
		if( j->io )
		{
			j->io = io_add( io_duplicate( j, block_io), j->io );
		}
		else
		{
			j->io=io_duplicate( j, block_io);				
		}
	}

	
	io_data_t *input_redirect;

	for( input_redirect = j->io; input_redirect; input_redirect = input_redirect->next )
	{
		if( (input_redirect->io_mode == IO_BUFFER) && 
			input_redirect->is_input )
		{
			/*
			  Input redirection - create a new gobetween process to take
			  care of buffering
			*/
			process_t *fake = halloc( j, sizeof(process_t) );
			fake->type = INTERNAL_BUFFER;
			fake->pipe_write_fd = 1;
			j->first_process->pipe_read_fd = input_redirect->fd;
			fake->next = j->first_process;
			j->first_process = fake;
			break;
		}
	}
	
	if( j->first_process->type==INTERNAL_EXEC )
	{
		/*
		  Do a regular launch -  but without forking first...
		*/
		signal_block();

		/*
		  setup_child_process makes sure signals are properly set
		  up. It will also call signal_unblock
		*/
		if( !setup_child_process( j, 0 ) )
		{
			/*
			  launch_process _never_ returns
			*/
			launch_process( j->first_process );
		}
		else
		{
			job_set_flag( j, JOB_CONSTRUCTED, 1 );
			j->first_process->completed=1;
			return;
		}

	}	

	pipe_read.fd=0;
	pipe_write.fd=1;
	pipe_read.io_mode=IO_PIPE;
	pipe_read.param1.pipe_fd[0] = -1;
	pipe_read.param1.pipe_fd[1] = -1;
	pipe_read.is_input = 1;

	pipe_write.io_mode=IO_PIPE;
	pipe_write.is_input = 0;
	pipe_read.next=0;
	pipe_write.next=0;
	pipe_write.param1.pipe_fd[0]=pipe_write.param1.pipe_fd[1]=-1;
	
	j->io = io_add( j->io, &pipe_write );
	
	signal_block();

	/*
	  See if we need to create a group keepalive process. This is
	  a process that we create to make sure that the process group
	  doesn't die accidentally, and is often needed when a
	  builtin/block/function is inside a pipeline, since that
	  usually means we have to wait for one program to exit before
	  continuing in the pipeline, causing the group leader to
	  exit.
	*/
	
	if( job_get_flag( j, JOB_CONTROL ) )
	{
		for( p=j->first_process; p; p = p->next )
		{
			if( p->type != EXTERNAL )
			{
				if( p->next )
				{
					needs_keepalive = 1;
					break;
				}
				if( p != j->first_process )
				{
					needs_keepalive = 1;
					break;
				}
				
			}
			
		}
	}
		
	if( needs_keepalive )
	{
		keepalive.pid = exec_fork();

		if( keepalive.pid == 0 )
		{
			keepalive.pid = getpid();
			set_child_group( j, &keepalive, 1 );
			pause();			
			exit(0);
		}
		else
		{
			set_child_group( j, &keepalive, 0 );			
		}
	}
	
	/*
	  This loop loops over every process_t in the job, starting it as
	  appropriate. This turns out to be rather complex, since a
	  process_t can be one of many rather different things.

	  The loop also has to handle pipelining between the jobs.
	*/

	for( p=j->first_process; p; p = p->next )
	{
		mypipe[1]=-1;
		skip_fork=0;
		
		pipe_write.fd = p->pipe_write_fd;
		pipe_read.fd = p->pipe_read_fd;
//		debug( 0, L"Pipe created from fd %d to fd %d", pipe_write.fd, pipe_read.fd );
		

		/* 
		   This call is used so the global environment variable array
		   is regenerated, if needed, before the fork. That way, we
		   avoid a lot of duplicate work where EVERY child would need
		   to generate it, since that result would not get written
		   back to the parent. This call could be safely removed, but
		   it would result in slightly lower performance - at least on
		   uniprocessor systems.
		*/
		if( p->type == EXTERNAL )
			env_export_arr( 1 );
		
		
		/*
		  Set up fd:s that will be used in the pipe 
		*/
		
		if( p == j->first_process->next )
		{
			j->io = io_add( j->io, &pipe_read );
		}
		
		if( p->next )
		{
//			debug( 1, L"%ls|%ls" , p->argv[0], p->next->argv[0]);
			
			if( exec_pipe( mypipe ) == -1 )
			{
				debug( 1, PIPE_ERROR );
				wperror (L"pipe");
				exec_error=1;
				break;
			}

			memcpy( pipe_write.param1.pipe_fd, mypipe, sizeof(int)*2);
		}
		else
		{
			/*
			  This is the last element of the pipeline.
			  Remove the io redirection for pipe output.
			*/
			j->io = io_remove( j->io, &pipe_write );
			
		}

		switch( p->type )
		{
			case INTERNAL_FUNCTION:
			{
				const wchar_t * orig_def;
				wchar_t * def=0;
				array_list_t *named_arguments;
				int shadows;
				

				/*
				  Calls to function_get_definition might need to
				  source a file as a part of autoloading, hence there
				  must be no blocks.
				*/

				signal_unblock();
				orig_def = function_get_definition( p->argv[0] );
				named_arguments = function_get_named_arguments( p->argv[0] );
				shadows = function_get_shadows( p->argv[0] );

				signal_block();
				
				if( orig_def )
				{
					def = halloc_register( j, wcsdup(orig_def) );
				}
				if( def == 0 )
				{
					debug( 0, _( L"Unknown function '%ls'" ), p->argv[0] );
					break;
				}

				parser_push_block( shadows?FUNCTION_CALL:FUNCTION_CALL_NO_SHADOW );
				
				current_block->param2.function_call_process = p;
				current_block->param1.function_call_name = halloc_register( current_block, wcsdup( p->argv[0] ) );
						

				/*
				  set_argv might trigger an event
				  handler, hence we need to unblock
				  signals.
				*/
				signal_unblock();
				parse_util_set_argv( p->argv+1, named_arguments );
				signal_block();
								
				parser_forbid_function( p->argv[0] );

				if( p->next )
				{
					io_buffer = io_buffer_create( 0 );					
					j->io = io_add( j->io, io_buffer );
				}
				
				internal_exec_helper( def, TOP, j->io );
				
				parser_allow_function();
				parser_pop_block();
				
				break;				
			}
			
			case INTERNAL_BLOCK:
			{
				if( p->next )
				{
					io_buffer = io_buffer_create( 0 );					
					j->io = io_add( j->io, io_buffer );
				}
								
				internal_exec_helper( p->argv[0], TOP, j->io );			
				break;
				
			}

			case INTERNAL_BUILTIN:
			{
				int builtin_stdin=0;
				int fg;
				int close_stdin=0;

				/*
				  If this is the first process, check the io
				  redirections and see where we should be reading
				  from.
				*/
				if( p == j->first_process )
				{
					io_data_t *in = io_get( j->io, 0 );
					
					if( in )
					{
						switch( in->io_mode )
						{
							
							case IO_FD:
							{
								builtin_stdin = in->param1.old_fd;
								break;
							}
							case IO_PIPE:
							{
								builtin_stdin = in->param1.pipe_fd[0];
								break;
							}
							
							case IO_FILE:
							{
								builtin_stdin=wopen( in->param1.filename,
                                              in->param2.flags, OPEN_MASK );
								if( builtin_stdin == -1 )
								{
									debug( 1, 
										   FILE_ERROR,
										   in->param1.filename );
									wperror( L"open" );
								}
								else
								{
									close_stdin = 1;
								}
								
								break;
							}
	
							case IO_CLOSE:
							{
								/*
								  FIXME:

								  When
								  requesting
								  that
								  stdin
								  be
								  closed,
								  we
								  really
								  don't
								  do
								  anything. How
								  should
								  this
								  be
								  handled?
								 */
								builtin_stdin = -1;
								
								break;
							}
							
							default:
							{
								builtin_stdin=-1;
								debug( 1, 
									   _( L"Unknown input redirection type %d" ),
									   in->io_mode);
								break;
							}
						
						}
					}
				}
				else
				{
					builtin_stdin = pipe_read.param1.pipe_fd[0];
				}

				if( builtin_stdin == -1 )
				{
					exec_error=1;
					break;
				}
				else
				{
					int old_out = builtin_out_redirect;
					int old_err = builtin_err_redirect;

					/* 
					   Since this may be the foreground job, and since
					   a builtin may execute another foreground job,
					   we need to pretend to suspend this job while
					   running the builtin, in order to avoid a
					   situation where two jobs are running at once.

					   The reason this is done here, and not by the
					   relevant builtins, is that this way, the
					   builtin does not need to know what job it is
					   part of. It could probably figure that out by
					   walking the job list, but it seems more robust
					   to make exec handle things.
					*/
					
					builtin_push_io( builtin_stdin );
					
					builtin_out_redirect = has_fd( j->io, 1 );
					builtin_err_redirect = has_fd( j->io, 2 );		

					fg = job_get_flag( j, JOB_FOREGROUND );
					job_set_flag( j, JOB_FOREGROUND, 0 );
					
					signal_unblock();
					
					p->status = builtin_run( p->argv, j->io );
					
					builtin_out_redirect=old_out;
					builtin_err_redirect=old_err;
					
					signal_block();
					
					/*
					  Restore the fg flag, which is temporarily set to
					  false during builtin execution so as not to confuse
					  some job-handling builtins.
					*/
					job_set_flag( j, JOB_FOREGROUND, fg );
				}
				
				/*
				  If stdin has been redirected, close the redirection
				  stream.
				*/
				if( close_stdin )
				{
					exec_close( builtin_stdin );
				}				
				break;				
			}
		}
		
		if( exec_error )
		{
			break;
		}
		
		switch( p->type )
		{

			case INTERNAL_BLOCK:
			case INTERNAL_FUNCTION:
			{
				int status = proc_get_last_status();
						
				/*
				  Handle output from a block or function. This usually
				  means do nothing, but in the case of pipes, we have
				  to buffer such io, since otherwise the internal pipe
				  buffer might overflow.
				*/
				if( !io_buffer )
				{
					/*
					  No buffer, so we exit directly. This means we
					  have to manually set the exit status.
					*/
					if( p->next == 0 )
					{
						proc_set_last_status( job_get_flag( j, JOB_NEGATE )?(!status):status);
					}
					p->completed = 1;
					break;
				}

				j->io = io_remove( j->io, io_buffer );
				
				io_buffer_read( io_buffer );
				
				if( io_buffer->param2.out_buffer->used != 0 )
				{
					pid = exec_fork();

					if( pid == 0 )
					{
						
						/*
						  This is the child process. Write out the contents of the pipeline.
						*/
						p->pid = getpid();
						setup_child_process( j, p );

						exec_write_and_exit(io_buffer->fd, 
											io_buffer->param2.out_buffer->buff,
											io_buffer->param2.out_buffer->used,
											status);
					}
					else
					{
						/* 
						   This is the parent process. Store away
						   information on the child, and possibly give
						   it control over the terminal.
						*/
						p->pid = pid;						
						set_child_group( j, p, 0 );
												
					}					
					
				}
				else
				{
					if( p->next == 0 )
					{
						proc_set_last_status( job_get_flag( j, JOB_NEGATE )?(!status):status);
					}
					p->completed = 1;
				}
				
				io_buffer_destroy( io_buffer );
				
				io_buffer=0;
				break;
				
			}


			case INTERNAL_BUFFER:
			{
		
				pid = exec_fork();
				
				if( pid == 0 )
				{
					/*
					  This is the child process. Write out the
					  contents of the pipeline.
					*/
					p->pid = getpid();
					setup_child_process( j, p );
					
					exec_write_and_exit( 1,
										 input_redirect->param2.out_buffer->buff, 
										 input_redirect->param2.out_buffer->used,
										 0);
				}
				else
				{
					/* 
					   This is the parent process. Store away
					   information on the child, and possibly give
					   it control over the terminal.
					*/
					p->pid = pid;						
					set_child_group( j, p, 0 );	
				}	

				break;				
			}
			
			case INTERNAL_BUILTIN:
			{
				int skip_fork;
				
				/*
				  Handle output from builtin commands. In the general
				  case, this means forking of a worker process, that
				  will write out the contents of the stdout and stderr
				  buffers to the correct file descriptor. Since
				  forking is expensive, fish tries to avoid it wehn
				  possible.
				*/

				/*
				  If a builtin didn't produce any output, and it is
				  not inside a pipeline, there is no need to fork
				*/
				skip_fork =
					( !sb_out->used ) &&
					( !sb_err->used ) &&
					( !p->next );
	
				/*
				  If the output of a builtin is to be sent to an internal
				  buffer, there is no need to fork. This helps out the
				  performance quite a bit in complex completion code.
				*/

				io_data_t *io = io_get( j->io, 1 );
				int buffer_stdout = io && io->io_mode == IO_BUFFER;
				
				if( ( !sb_err->used ) && 
					( !p->next ) &&
					( sb_out->used ) && 
					( buffer_stdout ) )
				{
					char *res = wcs2str( (wchar_t *)sb_out->buff );
					b_append( io->param2.out_buffer, res, strlen( res ) );
					skip_fork = 1;
					free( res );
				}

				for( io = j->io; io; io=io->next )
				{
					if( io->io_mode == IO_FILE && wcscmp(io->param1.filename, L"/dev/null" ))
					{
						skip_fork = 0;
					}
				}
				
				if( skip_fork )
				{
					p->completed=1;
					if( p->next == 0 )
					{
						debug( 3, L"Set status of %ls to %d using short circut", j->command, p->status );
						
						int status = proc_format_status(p->status);
						proc_set_last_status( job_get_flag( j, JOB_NEGATE )?(!status):status );
					}
					break;
				}

				/*
				  Ok, unfortunatly, we have to do a real fork. Bummer.
				*/
								
				pid = exec_fork();
				if( pid == 0 )
				{

					/*
					  This is the child process. Setup redirections,
					  print correct output to stdout and stderr, and
					  then exit.
					*/
					p->pid = getpid();
					setup_child_process( j, p );
					do_builtin_io( sb_out->used ? (wchar_t *)sb_out->buff : 0, sb_err->used ? (wchar_t *)sb_err->buff : 0 );
					
					exit( p->status );
						
				}
				else
				{
					/* 
					   This is the parent process. Store away
					   information on the child, and possibly give
					   it control over the terminal.
					*/
					p->pid = pid;
						
					set_child_group( j, p, 0 );
										
				}					
				
				break;
			}
			
			case EXTERNAL:
			{
				pid = exec_fork();
				if( pid == 0 )
				{
					/*
					  This is the child process. 
					*/
					p->pid = getpid();
					setup_child_process( j, p );
					launch_process( p );
					
					/*
					  launch_process _never_ returns...
					*/
				}
				else
				{
					/* 
					   This is the parent process. Store away
					   information on the child, and possibly fice
					   it control over the terminal.
					*/
					p->pid = pid;

					set_child_group( j, p, 0 );
															
				}
				break;
			}
			
		}

		if( p->type == INTERNAL_BUILTIN )
			builtin_pop_io();
				
		/* 
		   Close the pipe the current process uses to read from the
		   previous process_t
		*/
		if( pipe_read.param1.pipe_fd[0] >= 0 )
			exec_close( pipe_read.param1.pipe_fd[0] );
		/* 
		   Set up the pipe the next process uses to read from the
		   current process_t
		*/
		if( p->next )
			pipe_read.param1.pipe_fd[0] = mypipe[0];
		
		/* 
		   If there is a next process in the pipeline, close the
		   output end of the current pipe (the surrent child
		   subprocess already has a copy of the pipe - this makes sure
		   we don't leak file descriptors either in the shell or in
		   the children).
		*/
		if( p->next )
		{
			exec_close(mypipe[1]);
		}		
	}

	/*
	  The keepalive process is no longer needed, so we terminate it
	  with extreme prejudice
	*/
	if( needs_keepalive )
	{
		kill( keepalive.pid, SIGKILL );
	}
	
	signal_unblock();	

	debug( 3, L"Job is constructed" );

	j->io = io_remove( j->io, &pipe_read );

	for( tmp = block_io; tmp; tmp=tmp->next )
		j->io = io_remove( j->io, tmp );
	
	job_set_flag( j, JOB_CONSTRUCTED, 1 );

	if( !job_get_flag( j, JOB_FOREGROUND ) )
	{
		proc_last_bg_pid = j->pgid;
	}

	if( !exec_error )
	{
		job_continue (j, 0);
	}
	
}
예제 #16
0
int main(int argc, char *argv[])
{
  pid_t pid;
  char *line, *arg_list[255], name[BUFSIZ];
  char *tok;
  int status, i;
  int bgfg;

  line = malloc(sizeof(char) * 255);
    
  printf("\n\n\t***************************\n");
  printf("\t*  Welcome to our Shell!  *\n");
  printf("\t*  'exit' or 'quit' to    *\n");
  printf("\t*      exit! Enjoy!       *\n");
  printf("\t***************************\n\n");

  while (1)
  {
    printf("LainShell: ");
    fflush(stdout);
    fgets(line, 255, stdin);
    // If the last character is a newline we set it to a null-terminator
    if (line[strlen(line) - 1] == '\n')
      line[strlen(line) - 1] = '\0';

    if (strlen(line) == 0)
      continue;

    // Check for a pipe, if there is we'll go straight into the exec_pipe
    // function. For consistency we can't really reuse the below parent / child
    // code but we can reuse the process_args function.
    if (strstr(line, "|"))
    {
      exec_pipe(line);
      // Execute the pipe'd command and go to the next iteration of the while
      // loop. 
      continue;
    }

    // Tokenize based on ;
    tok = strtok(line, ";");
    while (tok != NULL)
    {
      // Save our position in the line so when we retokenize we're at the next
      // token. We can't use NULL because strtok in process_args overwrites it.
      line += strlen(tok) + 1;
      process_args(tok, arg_list, &bgfg);
      tok = strtok(line, ";");
      // If they typed exit or quit..we exit 
      if (strcmp(arg_list[0], "exit") == 0 || strcmp(arg_list[0], "quit") == 0)
        exit(0);
      
      pid = my_fork();
      
      if (pid == -1)
      {
        perror("Fork failed!\n");
        exit(1);
      }
      else if (pid > 0)
      {
        // If this flag was set by process args we run in the background
        if (bgfg == 1)
        {
          waitpid(pid, &status, WNOHANG);  
        }
        else
        {
          // Otherwise the foreground
          wait(&status);
        }
      }
      else
      {
        if (execvp(arg_list[0], arg_list) == -1)
        {
#ifdef MY_DEBUG
        DEBUG(arg_list[0]);
#endif
          int i = 0;
          while (arg_list[i] != NULL)
            printf("%d:\t%s\n", i, arg_list[i++]);
          perror("Child process could not exec");
          exit(22);
        }
      }
    }
  }
  
  return 0;
}
예제 #17
0
파일: pipe.c 프로젝트: Katasa/Epitech1_42sh
int	my_pipe(int i, char **command)
{
  exec_pipe(i, command);
  return (1);
}
예제 #18
0
/// Executes a process \p in job \j, using the read pipe \p pipe_current_read.
/// If the process pipes to a command, the read end of the created pipe is returned in
/// out_pipe_next_read. \returns true on success, false on exec error.
static bool exec_process_in_job(parser_t &parser, process_t *p, job_t *j,
                                autoclose_fd_t pipe_current_read,
                                autoclose_fd_t *out_pipe_next_read, const io_chain_t &all_ios,
                                size_t stdout_read_limit) {
    // The IO chain for this process. It starts with the block IO, then pipes, and then gets any
    // from the process.
    io_chain_t process_net_io_chain = j->block_io_chain();

    // See if we need a pipe.
    const bool pipes_to_next_command = !p->is_last_in_job;

    // The write end of any pipe we create.
    autoclose_fd_t pipe_current_write{};

    // The pipes the current process write to and read from. Unfortunately these can't be just
    // allocated on the stack, since j->io wants shared_ptr.
    //
    // The write pipe (destined for stdout) needs to occur before redirections. For example,
    // with a redirection like this:
    //
    //   `foo 2>&1 | bar`
    //
    // what we want to happen is this:
    //
    //    dup2(pipe, stdout)
    //    dup2(stdout, stderr)
    //
    // so that stdout and stderr both wind up referencing the pipe.
    //
    // The read pipe (destined for stdin) is more ambiguous. Imagine a pipeline like this:
    //
    //   echo alpha | cat < beta.txt
    //
    // Should cat output alpha or beta? bash and ksh output 'beta', tcsh gets it right and
    // complains about ambiguity, and zsh outputs both (!). No shells appear to output 'alpha',
    // so we match bash here. That would mean putting the pipe first, so that it gets trumped by
    // the file redirection.
    //
    // However, eval does this:
    //
    //   echo "begin; $argv "\n" ;end <&3 3<&-" | source 3<&0
    //
    // which depends on the redirection being evaluated before the pipe. So the write end of the
    // pipe comes first, the read pipe of the pipe comes last. See issue #966.
    shared_ptr<io_pipe_t> pipe_write;
    shared_ptr<io_pipe_t> pipe_read;

    // Write pipe goes first.
    if (pipes_to_next_command) {
        pipe_write.reset(new io_pipe_t(p->pipe_write_fd, false));
        process_net_io_chain.push_back(pipe_write);
    }

    // The explicit IO redirections associated with the process.
    process_net_io_chain.append(p->io_chain());

    // Read pipe goes last.
    if (!p->is_first_in_job) {
        pipe_read.reset(new io_pipe_t(p->pipe_read_fd, true));
        // Record the current read in pipe_read.
        pipe_read->pipe_fd[0] = pipe_current_read.fd();
        process_net_io_chain.push_back(pipe_read);
    }

    // This call is used so the global environment variable array is regenerated, if needed,
    // before the fork. That way, we avoid a lot of duplicate work where EVERY child would need
    // to generate it, since that result would not get written back to the parent. This call
    // could be safely removed, but it would result in slightly lower performance - at least on
    // uniprocessor systems.
    if (p->type == EXTERNAL) {
        // Apply universal barrier so we have the most recent uvar changes
        if (!get_proc_had_barrier()) {
            set_proc_had_barrier(true);
            env_universal_barrier();
        }
        env_export_arr();
    }

    // Set up fds that will be used in the pipe.
    if (pipes_to_next_command) {
        // debug( 1, L"%ls|%ls" , p->argv[0], p->next->argv[0]);
        int local_pipe[2] = {-1, -1};
        if (exec_pipe(local_pipe) == -1) {
            debug(1, PIPE_ERROR);
            wperror(L"pipe");
            job_mark_process_as_failed(j, p);
            return false;
        }

        // Ensure our pipe fds not conflict with any fd redirections. E.g. if the process is
        // like 'cat <&5' then fd 5 must not be used by the pipe.
        if (!pipe_avoid_conflicts_with_io_chain(local_pipe, all_ios)) {
            // We failed. The pipes were closed for us.
            wperror(L"dup");
            job_mark_process_as_failed(j, p);
            return false;
        }

        // This tells the redirection about the fds, but the redirection does not close them.
        assert(local_pipe[0] >= 0);
        assert(local_pipe[1] >= 0);
        memcpy(pipe_write->pipe_fd, local_pipe, sizeof(int) * 2);

        // Record our pipes.
        pipe_current_write.reset(local_pipe[1]);
        out_pipe_next_read->reset(local_pipe[0]);
    }

    // Execute the process.
    switch (p->type) {
        case INTERNAL_FUNCTION:
        case INTERNAL_BLOCK_NODE: {
            if (!exec_block_or_func_process(parser, j, p, all_ios, process_net_io_chain)) {
                return false;
            }
            break;
        }

        case INTERNAL_BUILTIN: {
            io_streams_t builtin_io_streams{stdout_read_limit};
            if (!exec_internal_builtin_proc(parser, j, p, pipe_read.get(), process_net_io_chain,
                                            builtin_io_streams)) {
                return false;
            }
            if (!handle_builtin_output(j, p, &process_net_io_chain, builtin_io_streams)) {
                return false;
            }
            break;
        }

        case EXTERNAL: {
            if (!exec_external_command(j, p, process_net_io_chain)) {
                return false;
            }
            break;
        }

        case INTERNAL_EXEC: {
            // We should have handled exec up above.
            DIE("INTERNAL_EXEC process found in pipeline, where it should never be. Aborting.");
            break;
        }
    }
    return true;
}
예제 #19
0
int poll_pids() {			//Poll all the alive/exited pids with WNOHANG - returns immediately without waiting for child process to exit.
	if (pid_list.starting==NULL) {
		return 0;
	}
	else {
		configure_status_file_and_mmap();
		int sleeptime=5,i;
		struct subprocess* current=pid_list.starting;
		int poll_status,status;
		lock_file();
		sprintf((char *)mmap_file_pointer,"");
		while (current->next!=NULL) {
			poll_status=waitpid(current->pid,&status,WNOHANG);
			if (poll_status==current->pid) {
				int exit_code=WEXITSTATUS(status);
				if (exit_code==0) {
					subprocess_count-=1;
					delete_list_element(current);
				}
				else if (exit_code==30 || exit_code==255 || exit_code==12) {
					if (exit_code==12) {sleeptime=1;}
					current->retries+=1;
					sleeptime=5;
					for (i=0;i<current->retries && sleeptime<320;i++) {sleeptime*=2;}
					strcpy(current->start_time,get_time_string());
					current->pid=exec_pipe(current->command,sleeptime);
				}
				else {
					subprocess_count-=1;
					delete_list_element(current);
				}
			}
			else if (poll_status==0) {
				put_info_in_status_file(current);
			}
			current=current->next;
		}
		poll_status=waitpid(current->pid,&status,WNOHANG);
		if (poll_status==current->pid) {
			int exit_code=WEXITSTATUS(status);
			if (exit_code==0) {
				subprocess_count-=1;
				delete_list_element(current);
			}
			else if (exit_code==30 || exit_code==255 || exit_code==12) {
				if (exit_code==12) {sleeptime=1;}
				current->retries+=1;
				sleeptime=5;
				for (i=0;i<current->retries && sleeptime<320;i++) {sleeptime*=2;}
				strcpy(current->start_time,get_time_string());
				printf("%s\n",current->command);
				current->pid=exec_pipe(current->command,sleeptime);
			}
			else {
				subprocess_count-=1;
				delete_list_element(current);
			}
		}
		else if (poll_status==0) {
			put_info_in_status_file(current);
		}
		unlock_file();
		clear_status_file();
		return 0;
	}
}