Esempio n. 1
0
USHORT TScreen::Initialize ()
{
   USHORT RetVal = FALSE;

   RxBytes = 0;
   RxPosition = 0;
   Running = TRUE;

#if defined(__NT__)
   AllocConsole ();
#endif

#if defined(__OS2__) || defined(__NT__)
   videoinit ();
#endif
   if ((wh = wopen (0, 0, (short)(24 - 1), 79, 5, LGREY|_BLACK, LGREY|_BLACK)) != -1) {
      wopen (24, 0, 24, 79, 5, WHITE|_BLUE, WHITE|_BLUE);
      wprintc (0, 22, WHITE|_BLUE, '�');
      wprintc (0, 43, WHITE|_BLUE, '�');
      wprintc (0, 58, WHITE|_BLUE, '�');
      wprintc (0, 69, WHITE|_BLUE, '�');
      wactiv (wh);
      showcur ();
      RetVal = TRUE;
   }
   videoupdate ();

   return (RetVal);
}
TInt CTestWideApi::wfdopen_ivalm1()
	{
	int wfd;
	int ret_wmkdir = wmkdir(L"C:\\ggg" , S_IWUSR);
	if(ret_wmkdir)
		{
	  	_LIT(Kerr , "Failed to make dir") ;
		INFO_PRINTF1(Kerr) ;
		return KErrGeneral ;		
		}				
	if((wfd=wopen(L"C:\\ggg\\lll.txt", O_WRONLY | O_CREAT | O_TRUNC, 0777))<0)
		{
	   	_LIT(Kopen,"Failed to open file");
		INFO_PRINTF1(Kopen);
		wrmdir(L"C:\\ggg");        		
		return KErrGeneral;
	    }
    FILE *fp =wfdopen(wfd ,NULL);
    if(NULL != fp)    	   
	    {
	 	wunlink(L"C:\\ggg\\lll.txt");
	   	wrmdir(L"C:\\ggg");
	   	return KErrGeneral;    	
	    }
	close(wfd);
    wunlink(L"C:\\ggg\\lll.txt");
	wrmdir(L"C:\\ggg");
    return KErrNone;  
	}
Esempio n. 3
0
/* Open wav file, check sample rate. Return WAVE* on success, NULL on error, and print the error messages to stderr. */
WAVE* open_wav(const char* infile, int verbose) {
	WAVE* wave = wopen(infile, "r");
	if (wave == NULL) {
		fprintf(stderr, "Error while opening wave file \"%s\".\n", infile);
		return NULL;
	}

	wgetheader(wave);
	if (werror(wave) != WAVE_OK) {
		fprintf(stderr, "Error while reading wave header from file \"%s\", error code: %d.\n", infile, werror(wave));
		return NULL;
	}

	if (verbose == 1) {
		printf("File info ============\n");
		printf("Wave file:   \"%s\"\n", infile);
		printf("Sample rate: %d Hz\n", wave->header.SampleRate);
		printf("Length:      %f s\n",
		((float)wave->header.Subchunk2Size / (wave->header.NumChannels * wave->header.BitsPerSample/8)) / (float)wave->header.SampleRate);
		printf("Sample bits: %d bits\n", wave->header.BitsPerSample);
		printf("Channels:    %d\n", wave->header.NumChannels);
	}

	if (wave->header.SampleRate != OPUS_SUPPORTED_FS) {
		fprintf(stderr, "Sample rate %d Hz is not supported. Only files with sample rate %d Hz are accepted.\n",
		        wave->header.SampleRate, OPUS_SUPPORTED_FS);
		wave = wclose(wave);
		return NULL;
	}

	return wave;
}
Esempio n. 4
0
/*******************************************************************************
	GESTION DE LA LIGNE DE COMMANDE
*******************************************************************************/
void LigneDeCommande()
{
	int	i;

sprintf(glb.div.log,"CommandLine: %i parameters\n",_argc-1);
_reportLog(LOG_INI);

	menuOff();
	for (i=1;i<_argc;i++)
	{
sprintf(glb.div.log,"CommandLine: %s\n",_argv[i]);
_reportLog(LOG_INI);
		if (_fexist(_argv[i],NULL))
			wopen(_argv[i]);
	}
	menuOn();
}
Esempio n. 5
0
/**
*
* thread = newthread(debug, id);
*
* Create a new thread.
*
**/
PUBLIC THREAD *newthread(DEBUG *debug, int id)
{
  THREAD *thread;
  WINDOW *window;

  if ((window = wopen(debug->display)) == NULL) return NULL;
  thread = NEW(THREAD);
  thread->id = id;
  thread->loc.module = NULL;
  thread->loc.line = 0;
  thread->block = NULL;
  thread->function = NULL;
  thread->window = window;
  InitSemaphore(&thread->sync, 0);
  /* ACE: Not sure about this */
  if (debug->threadlist.Head->Next == NULL) debug->thread = thread;
  AddHead(&debug->threadlist, &thread->node);
  return thread;
}
Esempio n. 6
0
/**
   Load contents of the backing file to memory
*/
static void history_load( history_mode_t *m )
{
    int fd;
    int ok=0;

    void *context;
    wchar_t *filename;

    if( !m )
        return;

    m->has_loaded=1;

    signal_block();

    context = halloc( 0, 0 );
    filename = history_filename( context, m->name, 0 );

    if( filename )
    {
        if( ( fd = wopen( filename, O_RDONLY ) ) > 0 )
        {
            off_t len = lseek( fd, 0, SEEK_END );
            if( len != (off_t)-1)
            {
                m->mmap_length = (size_t)len;
                if( lseek( fd, 0, SEEK_SET ) == 0 )
                {
                    if( (m->mmap_start = mmap( 0, m->mmap_length, PROT_READ, MAP_PRIVATE, fd, 0 )) != MAP_FAILED )
                    {
                        ok = 1;
                        history_populate_from_mmap( m );
                    }
                }
            }
            close( fd );
        }
    }

    halloc_free( context );
    signal_unblock();
}
Esempio n. 7
0
File: exec.c Progetto: 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);
	}
	
}
Esempio n. 8
0
File: exec.c Progetto: CodeMonk/fish
/**
   Make a copy of the specified io redirection chain, but change file
   redirection into fd redirection. This makes the redirection chain
   suitable for use as block-level io, since the file won't be
   repeatedly reopened for every command in the block, which would
   reset the cursor position.

   \return the transmogrified chain on sucess, or 0 on failiure
*/
static io_data_t *io_transmogrify( io_data_t * in )
{
	io_data_t *out;

	if( !in )
		return 0;
	
	out = malloc( sizeof( io_data_t ) );
	if( !out )
		DIE_MEM();
	
	out->fd = in->fd;
	out->io_mode = IO_FD;
	out->param2.close_old = 1;
	out->next=0;
		
	switch( in->io_mode )
	{
		/*
		  These redirections don't need transmogrification. They can be passed through.
		*/
		case IO_FD:
		case IO_CLOSE:
		case IO_BUFFER:
		case IO_PIPE:
		{
			memcpy( out, in, sizeof(io_data_t));
			break;
		}

		/*
		  Transmogrify file redirections
		*/
		case IO_FILE:
		{
			int fd;
			
			if( (fd=wopen( in->param1.filename, in->param2.flags, OPEN_MASK ) )==-1 )
			{
				debug( 1, 
					   FILE_ERROR,
					   in->param1.filename );
								
				wperror( L"open" );
				free( out );
				return 0;
			}	

			out->param1.old_fd = fd;
			break;
		}
	}
	
	if( in->next)
	{
		out->next = io_transmogrify( in->next );
		if( !out->next )
		{
			io_untransmogrify( in, out );
			return 0;
		}
	}
	
	return out;
}
Esempio n. 9
0
File: exec.c Progetto: CodeMonk/fish
/**
   Set up a childs io redirections. Should only be called by
   setup_child_process(). Does the following: First it closes any open
   file descriptors not related to the child by calling
   close_unused_internal_pipes() and closing the universal variable
   server file descriptor. It then goes on to perform all the
   redirections described by \c io.

   \param io the list of IO redirections for the child

   \return 0 on sucess, -1 on failiure
*/
static int handle_child_io( io_data_t *io )
{

	close_unused_internal_pipes( io );

	for( ; io; io=io->next )
	{
		int tmp;

		if( io->io_mode == IO_FD && io->fd == io->param1.old_fd )
		{
			continue;
		}

		if( io->fd > 2 )
		{
			/*
			  Make sure the fd used by this redirection is not used by e.g. a pipe. 
			*/
			free_fd( io, io->fd );
		}
				
		switch( io->io_mode )
		{
			case IO_CLOSE:
			{
				if( close(io->fd) )
				{
					debug( 0, _(L"Failed to close file descriptor %d"), io->fd );
					wperror( L"close" );
				}
				break;
			}

			case IO_FILE:
			{
				if( (tmp=wopen( io->param1.filename,
						io->param2.flags, OPEN_MASK ) )==-1 )
				{
					if( ( io->param2.flags & O_EXCL ) &&
					    ( errno ==EEXIST ) )
					{
						debug( 1, 
						       NOCLOB_ERROR,
						       io->param1.filename );
					}
					else
					{
						debug( 1, 
						       FILE_ERROR,
						       io->param1.filename );
										
						wperror( L"open" );
					}
					
					return -1;
				}
				else if( tmp != io->fd)
				{
					/*
					  This call will sometimes fail, but that is ok,
					  this is just a precausion.
					*/
					close(io->fd);
							
					if(dup2( tmp, io->fd ) == -1 )
					{
						debug( 1, 
							   FD_ERROR,
							   io->fd );
						wperror( L"dup2" );
						return -1;
					}
					exec_close( tmp );
				}				
				break;
			}
			
			case IO_FD:
			{
				/*
				  This call will sometimes fail, but that is ok,
				  this is just a precausion.
				*/
				close(io->fd);

				if( dup2( io->param1.old_fd, io->fd ) == -1 )
				{
					debug( 1, 
						   FD_ERROR,
						   io->fd );
					wperror( L"dup2" );
					return -1;
				}
				break;
			}
			
			case IO_BUFFER:
			case IO_PIPE:
			{
				int write_pipe;
				
				write_pipe = !io->is_input;
/*
				debug( 0,
					   L"%ls %ls on fd %d (%d %d)", 
					   write_pipe?L"write":L"read", 
					   (io->io_mode == IO_BUFFER)?L"buffer":L"pipe",
					   io->fd,
					   io->param1.pipe_fd[0],
					   io->param1.pipe_fd[1]);
*/
				if( dup2( io->param1.pipe_fd[write_pipe], io->fd ) != io->fd )
				{
					debug( 1, PIPE_ERROR );
					wperror( L"dup2" );
					return -1;
				}

				if( write_pipe ) 
				{
					exec_close( io->param1.pipe_fd[0]);
					exec_close( io->param1.pipe_fd[1]);
				}
				else
				{
					exec_close( io->param1.pipe_fd[0] );
				}
				break;
			}
			
		}
	}

	return 0;
	
}
Esempio n. 10
0
File: io.c Progetto: bhanug/harvey
/*
 * Attempt to install a new page.  If t==0 we are creating.
 * Otherwise, we are editing and t must be set to the current
 * version (t is the version we started with) to avoid conflicting
 * writes.
 *
 * If there is a conflicting write, we still write the page to 
 * the history file, but mark it as a failed write.
 */
int
writepage(int num, uint32_t t, String *s, char *title)
{
	char tmp[40], tmplock[40], err[ERRMAX], hist[40], *p;
	int conflict, lfd, fd;
	Biobuf *b;
	String *os;

	sprint(tmp, "d/%d", num);
	sprint(tmplock, "d/L.%d", num);
	sprint(hist, "d/%d.hist", num);
	if((lfd = getlock(tmplock)) < 0)
		return -1;

	conflict = 0;
	if(b = wBopen(tmp, OREAD)){
		Brdline(b, '\n');	/* title */
		if(p = Brdline(b, '\n'))		/* version */
			p[Blinelen(b)-1] = '\0';
		if(p==nil || p[0] != 'D'){
			snprint(err, sizeof err, "bad format in extant file");
			conflict = 1;
		}else if(strtoul(p+1, 0, 0) != t){
			os = Brdstring(b);	/* why read the whole file? */
			p = strchr(s_to_c(s), '\n');
			if(p!=nil && strcmp(p+1, s_to_c(os))==0){	/* ignore dup write */
				close(lfd);
				s_free(os);
				Bterm(b);
				return 0;
			}
			s_free(os);
			snprint(err, sizeof err, "update conflict %lud != %s", t, p+1);
			conflict = 1;
		}
		Bterm(b);
	}else{
		if(t != 0){
			close(lfd);
			werrstr("did not expect to create");
			return -1;
		}
	}

	if((fd = wopen(hist, OWRITE)) < 0){
		if((fd = wcreate(hist, OWRITE, 0666)) < 0){
			close(lfd);
			return -1;
		}else
			fprint(fd, "%s\n", title);
	}
	if(seek(fd, 0, 2) < 0
	|| (conflict && write(fd, "X\n", 2) != 2)
	|| write(fd, s_to_c(s), s_len(s)) != s_len(s)){
		close(fd);
		close(lfd);
		return -1;
	}
	close(fd);

	if(conflict){
		close(lfd);
		voidcache(num);
		werrstr(err);
		return -1;
	}

	if((fd = wcreate(tmp, OWRITE, 0666)) < 0){
		close(lfd);
		voidcache(num);
		return -1;
	}
	if(write(fd, title, strlen(title)) != strlen(title)
	|| write(fd, "\n", 1) != 1
	|| write(fd, s_to_c(s), s_len(s)) != s_len(s)){
		close(fd);
		close(lfd);
		voidcache(num);
		return -1;
	}
	close(fd);
	close(lfd);
	voidcache(num);
	return 0;
}
Esempio n. 11
0
int main(int argc, char** argv) {
    u_char *packet;
    int i;
    uint32_t ck;
    
    struct sockaddr *sin_src;
    struct sockaddr *sin_net;
    struct sockaddr *sin_dst;
    struct sockaddr *sin_mask;
    struct ip6_pseudo_hdr ps_hdr;
    int sendsize;
    struct options opts;
    FILE* fp_domain;
    char * domain;
    struct writer_info wi;
    int pkt_len;
    
    double speed_limit;
    double pkt_sent;

    

    int q_class;
    int q_type;


    pthread_t thread;


    pthread_create(&thread,NULL,readliner,&speed_limit);

    sleeper = 50;
    pkt_sent = 0;
    speed_limit = 50000;
    /**
     * 
     * headers
     */
    struct ether_header *eth;
    struct iphdr *ip;
    struct ip6_hdr *ip6;
    struct udphdr *udp;
    u_char *dns;
    u_char dns_opt[] = {00, 00, 0x29, 0x08, 00, 00, 00, 00, 00, 00, 00};
    setoptions(argc, argv, &opts);
    
    


    

    

    

    packet = calloc(sizeof (u_char) * 4096, 1);
    sin_src = calloc(sizeof (struct sockaddr_storage), 1);
    sin_net = calloc(sizeof (struct sockaddr_storage), 1);
    sin_dst = calloc(sizeof (struct sockaddr_storage), 1);
    sin_mask = calloc(sizeof (struct sockaddr_storage), 1);
    domain = calloc(sizeof (char) * 1024, 1);
    //domain = NULL;
    
    if (packet == NULL ||
            sin_src == NULL ||
            sin_net == NULL ||
            sin_dst == NULL ||
            sin_mask == NULL ||
            domain == NULL) {
        return -1;
    }

    /**
     * 
     * ETHERNET static
     */

    eth = (struct ether_header *) packet;

    if (ether_setaddr(opts.smac, &(eth->ether_shost)) < 0) {
        fprintf(stderr, "smac error:%s\n");
        return 1;
    }
    if (ether_setaddr(opts.dmac, &(eth->ether_dhost)) < 0) {
        fprintf(stderr, "dmac error\n");
        return 1;
    }

    /**
     * 
     * IP static
     */
    if (getipaddr(opts.dip, sin_dst, opts.family) < 0) {
        fprintf(stderr, "dip error\n");
        return 2;
    }
    if (getipaddr(opts.snet, sin_net, opts.family) < 0) {
        fprintf(stderr, "sip error\n");
        return 2;
    }

    if (sin_net->sa_family != sin_dst->sa_family) {
        fprintf(stderr, "IP family doesn't match\n");
        return 2;
    }

    set_mask(sin_mask, sin_net->sa_family, opts.smask);

    if (sin_net->sa_family == AF_INET) {
        eth->ether_type = htons(ETHERTYPE_IP);

        ip = (struct iphdr *) (packet + ETHER_HDR_LEN);
        ip->daddr = ((struct sockaddr_in *) sin_dst)->sin_addr.s_addr;


        ip->version = 4;
        ip->ihl = 5; // no opts
        ip->frag_off = 0;
        ip->id = 0;
        ip->protocol = IPPROTO_UDP;
        ip->tos = 0;
        ip->ttl = IPDEFTTL;


        udp = (struct udphdr *) (((void *) ip) + IP_HDR_LEN);
    } else if (sin_net->sa_family == AF_INET6) {
        eth->ether_type = htons(ETHERTYPE_IPV6);

        ip6 = (struct ip6_hdr *) (packet + ETHER_HDR_LEN);
        ip6->ip6_vfc = 6 << 4;
        ip6->ip6_hlim = IPDEFTTL;
        ip6->ip6_nxt = IPPROTO_UDP;

        memcpy(&(ip6->ip6_dst), &(((struct sockaddr_in6 *) sin_dst)->sin6_addr), 16);

        udp = (struct udphdr *) (((void *) ip6) + IP6_HDR_LEN);
    } else {
        fprintf(stderr, "Family unknown\n");
        return 2;
    }

    /**
     * 
     * UDP static
     */
    //udp->check = 0;
    udp->dest = htons(53);

    /**
     * 
     * DNS static
     */
    dns = (u_char *) (((void *) udp) + UDP_HDR_LEN);


    wopen(&wi,&opts);
    
    init_domain_file(&fp_domain, opts.in_file_name);
    if (fp_domain == NULL) {
        fprintf(stderr, "Can't open queries file\n");
        wclose(&wi);
        
        return 4;
    }
    for (i = 0; i < opts.count; i++) {
	if(pkt_sent >= sleeper) {
		speed_calc(pkt_sent,speed_limit, &sleeper);
                pkt_sent = 0;
		usleep(1);
	}
        /**
         * 
         * DNS dynamic
         */
        if(nextdomain(fp_domain, &domain, &q_type, &q_class)) {
            printf("Can't read next domain\n");
            exit(1);
        }

        sendsize = res_mkquery(QUERY, domain, q_class, q_type, NULL,
                0, NULL, dns, PACKETSZ);
        dns[11] = 1;
        memcpy(dns + sendsize, dns_opt, 11);
        sendsize += 11;
        /**
         * 
         * UDP dynamic
         */
        udp->source = htons(rand());
        udp->len = htons(sendsize + UDP_HDR_LEN);
        udp->check = 0;
        /**
         * 
         * IP dynamic
         */
        get_rand_addr(sin_net, sin_mask, sin_src);

        if (sin_net->sa_family == AF_INET) {
            ip->saddr = ((struct sockaddr_in *) sin_src)->sin_addr.s_addr;
            ip->tot_len = htons(sendsize + UDP_HDR_LEN + (ip->ihl * 4));
            pkt_len = sendsize + UDP_HDR_LEN + (ip->ihl * 4) + ETHER_HDR_LEN;

            ip->check = 0;
            ip->check = inet_cksum(ip, (ip->ihl * 4), 0);
        } else if (sin_net->sa_family == AF_INET6) {
            memcpy(&(ip6->ip6_src), &(((struct sockaddr_in6 *) sin_src)->sin6_addr), 16);
            ip6->ip6_plen = htons(sendsize + UDP_HDR_LEN);
            pkt_len = sendsize + UDP_HDR_LEN + sizeof (struct ip6_hdr) +ETHER_HDR_LEN;

            ps_hdr.src = ip6->ip6_src;
            ps_hdr.dst = ip6->ip6_dst;
            ps_hdr.len = udp->len;
            ps_hdr.nh = ntohs(17);

            ck = inet_cksum(&ps_hdr, sizeof (ps_hdr), 0);
            udp->check = inet_cksum(udp, sendsize + UDP_HDR_LEN, (~ck)&0xffff);
        }


        
        
        if (pkt_len > opts.mtu) {
            fprintf(stderr, "too long: %s needs %d MTU is %d\n", domain, pkt_len, opts.mtu);
        } else {
            wwrite(&wi,packet,pkt_len);
        }
	pkt_sent++;
    }

    wclose(&wi);
    fclose(fp_domain);

    return (EXIT_SUCCESS);
}
Esempio n. 12
0
File: io.c Progetto: bhanug/harvey
void
currentmap(int force)
{
	char *p, *q, *r;
	int lfd, fd, m, n;
	Dir *d;
	Map *nmap;
	char *err = nil;

	lfd = -1;
	fd = -1;
	d = nil;
	nmap = nil;
	if(!force && map && map->t+Tcache >= time(0))
		return;

	wlock(&maplock);
	if(!force && map && map->t+Tcache >= time(0))
		goto Return;

	if((lfd = getlock("d/L.map")) < 0){
		err = "can't lock";
		goto Return;
	}

	if((d = wdirstat("d/map")) == nil)
		goto Return;

	if(map && d->qid.path == map->qid.path && d->qid.vers == map->qid.vers){
		map->t = time(0);
		goto Return;
	}

	if(d->length > Maxmap){
		//LOG
		err = "too long";
		goto Return;
	}

	if((fd = wopen("d/map", OREAD)) < 0)
		goto Return;

	nmap = emalloc(sizeof *nmap);
	nmap->buf = emalloc(d->length+1);
	n = readn(fd, nmap->buf, d->length);
	if(n != d->length){
		err = "bad length";
		goto Return;
	}
	nmap->buf[n] = '\0';

	n = 0;
	for(p=nmap->buf; p; p=strchr(p+1, '\n'))
		n++;
	nmap->el = emalloc(n*sizeof(nmap->el[0]));

	m = 0;
	for(p=nmap->buf; p && *p && m < n; p=q){
		if(q = strchr(p+1, '\n'))
			*q++ = '\0';
		nmap->el[m].n = strtol(p, &r, 10);
		if(*r == ' ')
			r++;
		else
			{}//LOG?
		nmap->el[m].s = strcondense(r, 1);
		m++;
	}
	//LOG if m != n

	nmap->qid = d->qid;
	nmap->t = time(0);
	nmap->nel = m;
	qsort(nmap->el, nmap->nel, sizeof(nmap->el[0]), mapcmp);
	if(map)
		closemap(map);
	map = nmap;
	incref(map);
	nmap = nil;
	
Return:
	free(d);
	if(nmap){
		free(nmap->el);
		free(nmap->buf);
		free(nmap);
	}
	if(map == nil)
		sysfatal("cannot get map: %s: %r", err);

	if(fd >= 0)
		close(fd);
	if(lfd >= 0)
		close(lfd);
	wunlock(&maplock);
}
Esempio n. 13
0
TInt CTestWideApi::wfdopen_ivalm()
	{
	TPtrC nameRead;
	_LIT( KString, "Parameter1" );	    	
	TBool res = GetStringFromConfig(ConfigSection(), KString, nameRead);
	if(!res)
		{
		_LIT(Kerr , "Failed to read string") ;
		INFO_PRINTF1(Kerr) ;
		return KErrGeneral ;
		}	
	int ret_wmkdir = wmkdir(L"C:\\ggg" , S_IWUSR);
	if((errno == EEXIST) || (!ret_wmkdir))
		{
		TBuf8<100> buf;
	
		int wfd;
		buf.Copy(nameRead);
		char* filemode = (char*) buf.Ptr();
		filemode[buf.Length()]='\0';
		wchar_t *dmode = (wchar_t *)malloc(30*sizeof(wchar_t));
		if(dmode==NULL)
			{
			wrmdir(L"C:\\ggg");        								
			return KErrNoMemory;							
			}						
		size_t siz = mbstowcs(dmode, filemode, 30);
		wunlink(L"C:\\ggg\\lll.txt");
		if((wfd=wopen(L"C:\\ggg\\lll.txt", O_WRONLY | O_CREAT | O_TRUNC, 0777))<0)
	        {
        	_LIT(Kopen,"Failed to open file");
			INFO_PRINTF1(Kopen);
			wrmdir(L"C:\\ggg");      
			free(dmode) ;
			return KErrGeneral;
	        }
        else
	        {
	         FILE *fp =wfdopen(wfd ,dmode);
        	 if(NULL == fp)    	
        	 	{
	    	 	_LIT(Kopen,"wfdopen failed");
				INFO_PRINTF1(Kopen);
				close(wfd);
				wunlink(L"C:\\ggg\\lll.txt");
				wrmdir(L"C:\\ggg"); 
				free(dmode) ;     		
				return KErrNone;
        	 	}
        	 else
        	    { 
    	    	wunlink(L"C:\\ggg\\lll.txt");
   				wrmdir(L"C:\\ggg");
   				free(dmode) ;
    	    	return KErrGeneral;
        	    }        	 	
    	    }      
      	}
	else
		{
	  	_LIT(Kerr , "Failed to make dir") ;
		INFO_PRINTF1(Kerr) ;
		wunlink(L"C:\\ggg\\lll.txt");
   		wrmdir(L"C:\\ggg");
		return KErrGeneral ;
		}
	}
Esempio n. 14
0
TInt CTestWideApi::wfreopen_val()
	{
	TPtrC nameRead;
	_LIT( KString, "Parameter1" );
	TBool res = GetStringFromConfig(ConfigSection(), KString, nameRead);
	if(!res)
		{
		_LIT(Kerr , "Failed to read string") ;
		INFO_PRINTF1(Kerr) ;
		return KErrGeneral ;
		}
    int ret_wmkdir = wmkdir(L"C:\\ggg" , S_IWUSR);
	if((errno == EEXIST) || (!ret_wmkdir))
		{
		TBuf8<100> buf;	
		int wfd;
		FILE *fp;
		buf.Copy(nameRead);
		char c = 'z';
		char* filename = (char*) buf.Ptr();
		filename[buf.Length()]='\0';
		wchar_t *pathName = (wchar_t *)malloc(30*sizeof(wchar_t));
		if(pathName==NULL)
			{
			wrmdir(L"C:\\ggg");        								
			return KErrNoMemory;							
			}							
		size_t siz = mbstowcs(pathName, filename, 30);
		wunlink(pathName) ;
        if((wfd=wopen(pathName, O_WRONLY | O_CREAT | O_TRUNC, 0666))<0)
        	{
        	_LIT(Kopen,"Failed to open file");
			INFO_PRINTF1(Kopen);
			wrmdir(L"C:\\ggg");  
			free(pathName);      		
			return KErrGeneral;
        	}
        else
        	{
             write(wfd,&c,1); 	
        	}
        close(wfd);
        if((fp=wfreopen(pathName ,L"r",stdin))==NULL) 
			{
			_LIT(Kropen , " Failed to reopen file " ) ;
			INFO_PRINTF1(Kropen) ;
			wrmdir(L"C:\\ggg");  
			free(pathName);       		
			return KErrGeneral;
			}
     	char * filen="C:\\tem.txt";
     	unlink(filen);
     	int fd=open(filen, O_WRONLY | O_CREAT | O_TRUNC, 0666);
		if(fd<0)
			{
			_LIT(Kopen,"Failed to open file");
			INFO_PRINTF1(Kopen);
			wrmdir(L"C:\\ggg");        		
			free(pathName); 
			return KErrGeneral  ;
			}
		else
			{
		   	write(fd,&c,1);
			}
		close(fd); 
	    fclose(fp); 
	    unlink(filen);
		wunlink(pathName);	
		wrmdir(L"C:\\ggg");  
		free(pathName);       		
        return KErrNone ;
	    }
	else
		{
	  	_LIT(Kerr , "Failed to make dir") ;
		INFO_PRINTF1(Kerr) ;
		return KErrGeneral ;
		}
	}
Esempio n. 15
0
// -----------------------------------------------------------------------------
//Function Name : wfdopen_val
//API Tested : wfdopen
//TestCase Description: testing the behaviour of wfdopen for valid arguments
// initialized to NULL.
// -----------------------------------------------------------------------------  
TInt CTestWideApi::wfdopen_val()
	{
	TPtrC nameRead;
	wchar_t *pathName = NULL;
	_LIT( KString, "Parameter1" );	    	
	TBool res = GetStringFromConfig(ConfigSection(), KString, nameRead);
	if(!res)
		{
		_LIT(Kerr , "Failed to read string") ;
		INFO_PRINTF1(Kerr) ;
		return KErrGeneral ;
		}		
	int ret_wmkdir = wmkdir(L"C:\\ggg" , S_IWUSR);
	if((errno == EEXIST) || (!ret_wmkdir))
		{
		TBuf8<100> buf;	
		int wfd;
		FILE *fp;
		buf.Copy(nameRead);
		char* filename = (char*) buf.Ptr();
		filename[buf.Length()]='\0';
		pathName = (wchar_t *)malloc(30*sizeof(wchar_t));
		if(pathName==NULL)
			{
			wrmdir(L"C:\\ggg");        								
			return KErrNoMemory;							
			}						
		size_t siz = mbstowcs(pathName, filename, 30);
		wunlink(pathName) ;
        if((wfd=wopen(pathName, O_WRONLY | O_CREAT | O_TRUNC, 0666))<0)
	        {
        	_LIT(Kopen,"Failed to open file");
			INFO_PRINTF1(Kopen);
			wrmdir(L"C:\\ggg"); 
			free(pathName);       		
			return KErrGeneral;
	        }
        else
	        {
        	 if(NULL == (fp =wfdopen(wfd ,L"w")))    	
        	 	{
        	 	_LIT(Kopen,"wfdopen failed");
				INFO_PRINTF1(Kopen);
				wrmdir(L"C:\\ggg"); 
				free(pathName);       		
				return KErrGeneral;
        	 	}
        	 char *buffer="Writing to the file";
        	 size_t size=strlen(buffer);        	 
        	 if(size!=(fwrite(buffer,1,size,fp)))
        	 	{
        	 	_LIT(Kopen,"fwrite failed");
				INFO_PRINTF1(Kopen);
				wrmdir(L"C:\\ggg");    
				free(pathName);    		
				return KErrGeneral;
        	 	}        	 	
    	    }
       fclose(fp);
       wunlink(pathName);
       wrmdir(L"C:\\ggg");
       free(pathName);        		
	   return KErrNone;
	    }
	else
		{
	  	_LIT(Kerr , "Failed to make dir") ;
		INFO_PRINTF1(Kerr) ;
		wrmdir(L"C:\\ggg");
		return KErrGeneral ;
		}
	}
Esempio n. 16
0
int main(int argc, char *argv[]) {
    int fin=-1, fout=-1, f=0;
    char buf[8192], xstring[128]="";
    int rlen, wlen, blen=512, argi, r=0, w=0;

    for(argi=1; argi<argc || argc==1; argi++) {
        if (argc==1 || !strcmp(argv[argi], "--help")) {
            fprintf(stderr, "inlet    [-v|-a|-bN|-p1|-p2|--help] <pipename1 in> [-|<pipename2 out>]\n");
            fprintf(stderr, "Flags:   -v=verbose; -bN=N byte buffer (i.e. -b512); -pN=open pipe N first\n");
            fprintf(stderr, "         -a=always reopen p1 even if p1 closes (note: p2 will never close)\n");
            fprintf(stderr, "Info:    inlet reads from pipe1 to pipe2; if pipe1 closes it is reopened automatically.\n");
            fprintf(stderr, "Purpose: Trick an application into believing that it is reading from a single file (i.e. pipe2):\n");
            fprintf(stderr, "           1) when in fact multiple writers are dynamically opening and closing to pipe1.\n");
            fprintf(stderr, "           2) or from a remote shell (i.e. rsh) or remote machine\n");
            fprintf(stderr, "         while pipe2 is always kept open by the inlet program.\n");
            fprintf(stderr, "Notes:   Pipes can be created by the mkfifo command.\n");
            fprintf(stderr, "         Each pipe open is sequentially suspended (i.e. blocked) until another task accesses it.\n");
            fprintf(stderr, "         O_NDELAY and O_NONBLOCK are not used by inlet (see unix \"man -s 2 open\")\n");
            fprintf(stderr, "Example: mkfifo p1 p2; inlet -v -a p1 p2 & ; cat p2 & ; echo hello >p1; echo Konichiwa >p1;\n");
            fprintf(stderr, "\n");
            exit(1);
        }
        else if (!strcmp(argv[argi],  "-v"))    {
            vflag=1;
        }
        else if (!strcmp(argv[argi],  "-a"))    {
            aflag=1;
        }
        else if (!strncmp(argv[argi], "-b", 2)) {
            blen=atoi(argv[argi]+2);
        }
        else if (!strcmp(argv[argi],  "-p1"))   {
            pflag=1;
        }
        else if (!strcmp(argv[argi],  "-p2"))   {
            pflag=2;
        }
        else if ( strncmp(argv[argi], "-",  1) || strlen(argv[argi])>1) {
            if      (f==0) {
                f++;
                r=argi;
            }
            else if (f==1) {
                f++;
                w=argi;
            }
            else           {
                fprintf(stderr, "inlet: unexpected pipename or filename \"%s\"\n", argv[argi]);
                exit(1);
            }
        }
    }
    if (f!=2) {
        fprintf(stderr, "inlet: missing in or out pipe names\n");
        exit(1);
    }

    if    (vflag) {
        fprintf(stderr, "inlet: bufsize=%d (-b%d)\n", blen, blen);
    }

    if (pflag==1) {
        fin=ropen(argv[r]);
        fout=wopen(argv[w]);
    }
    else          {
        fout=wopen(argv[w]);
        fin=ropen(argv[r]);
    }

    if (vflag) {
        fprintf(stderr, "inlet: start reading pipe \"%s\" writing to \"%s\"\n", argv[r], argv[w]);
    }
    for(;;) {
        rlen = read(fin, buf, blen);
        if (vflag) {
            fprintf(stderr, "inlet: %d=read(\"%s\",buf,%d bytes);\n", rlen, argv[r], blen);
        }

        if      (rlen==0) {
            close(fin);
            if (aflag) {
                fin=ropen(argv[r]);
            }
            else {
                break;
            } /* eof on pipe1 */
        }
        else if (rlen<0) {
            if (vflag) {
                fprintf(stderr, "inlet: read error from \"%s\"\n", rlen, argv[r]);
            }
            perror("inlet: read");
            return 1;
        }

        wlen=write(fout, buf, rlen);
        if (vflag) {
            fprintf(stderr, "inlet: %d=write(\"%s\",buf,%d bytes);\n", wlen, argv[w], rlen);
        }
        if (wlen != rlen) {
            if (vflag) {
                fprintf(stderr, "inlet: write(\"%s\") length %d != read length %d\n", argv[w], wlen, rlen);
            }
            perror("inlet: write");
            return 1;
        }
    }
    return 0;
}
Esempio n. 17
0
File: io.c Progetto: bhanug/harvey
int
allocnum(char *title, int mustbenew)
{
	char *p, *q;
	int lfd, fd, n;
	Biobuf b;

	if(strcmp(title, "map")==0 || strcmp(title, "new")==0){
		werrstr("reserved title name");
		return -1;
	}

	if(title[0]=='\0' || strpbrk(title, "/<>:?")){
		werrstr("invalid character in name");
		return -1;
	}
	if((n = nametonum(title)) >= 0){
		if(mustbenew){
			werrstr("duplicate title");
			return -1;
		}
		return n;
	}

	title = estrdup(title);
	strcondense(title, 1);
	strlower(title);
	if(strchr(title, '\n') || strlen(title) > 200){
		werrstr("bad title");
		free(title);
		return -1;
	}

	if((lfd = getlock("d/L.map")) < 0){
		free(title);
		return -1;
	}

	if((fd = wopen("d/map", ORDWR)) < 0){	// LOG?
		close(lfd);
		free(title);
		return -1;
	}

	/*
	 * What we really need to do here is make sure the 
	 * map is up-to-date, then make sure the title isn't
	 * taken, and then add it, all without dropping the locks.
	 *
	 * This turns out to be a mess when you start adding
	 * all the necessary dolock flags, so instead we just
	 * read through the file ourselves, and let our 
	 * map catch up on its own.
	 */
	Binit(&b, fd, OREAD);
	n = 0;
	while(p = Brdline(&b, '\n')){
		p[Blinelen(&b)-1] = '\0';
		n = atoi(p)+1;
		q = strchr(p, ' ');
		if(q == nil)
			continue;
		if(strcmp(q+1, title) == 0){
			free(title);
			close(fd);
			close(lfd);
			if(mustbenew){
				werrstr("duplicate title");
				return -1;
			}else
				return n;
		}
	}

	seek(fd, 0, 2);	/* just in case it's not append only */
	fprint(fd, "%d %s\n", n, title);
	close(fd);
	close(lfd);
	free(title);
	/* kick the map */
	currentmap(1);
	return n;
}
Esempio n. 18
0
/* Use script to produce jpeg frames */
void script_animate (int iw)
{
    char buf[SCRIPT_LINE_SIZE],output[SCRIPT_LINE_SIZE],*ptr;
    int i,hascontent,quality,frames;
    FILE *fp;
    glob_t globbuf;
    
    strcpy(buf, "scr_anim");
    if (!(fp=ropen(buf)))
    {
        printf ("\nAnimation script \"%s\" does not exist,\n", buf);
        xterm_get_focus(iw); clear_stdin_buffer();
        if (!strcasecmp("y", readline_gets
                        ("Do you want a default one created (y/n)?","y")))
        {
            numerically_sorted_glob (config_fname, &globbuf);
            fp=wopen(buf);
            fprintf (fp, "%d\n", AX_JPG_DEF_QUALITY);
            for (i=0; i<globbuf.gl_pathc; i++)
                fprintf (fp, "%s Jpg/%05d.jpg\n", globbuf.gl_pathv[i], i);
            globfree (&globbuf);
            fclose(fp);
            fp = ropen(buf);
        }
        else
        {
            xterm_release_focus(iw);
            return;
        }
    }
    if (!(ptr=fgets(buf,SCRIPT_LINE_SIZE,fp)))
    {
        printf ("\nThere is nothing in animation script \"%s\".\n", buf);
        fclose (fp);
        return;
    }
    for (hascontent=i=0; (buf[i]!=EOS) &&
             (ISDIGIT(buf[i]) || ISBLANK(buf[i]) || (buf[i]=='\n')); i++)
        if (ISALNUM(buf[i])) hascontent=1;
    if (!hascontent)
    {
        printf ("\nThere is no content in animation script \"%s\".\n", buf);
        fclose (fp);
        return;
    }
    if (buf[i] == EOS)
    {
        sscanf (buf, "%d", &quality);
        if ((quality<0) || (quality>100))
        {
            printf ("\nquality = %d is out of valid range ([0,100]).\n",
                    quality);
            return;
        }
        else printf ("\nquality = %d\n", quality);
        ptr = fgets(buf,SCRIPT_LINE_SIZE,fp);
    }
    else quality = AX_JPG_DEF_QUALITY;
    frames = 0;
    /* If bonds are not on now, there is no need to refresh */
    temporary_disable_bond = !n[iw].bond_mode;
    /* cylinder data structure during the rendering.        */
    while (ptr)
    {
        buf[SCRIPT_LINE_CHAR] = EOS;
        sscanf (buf, "%s %s", config_fname, output);
        reload_config (iw, FALSE);
        paint_scene(iw);
        AX_dump(iw); AX_show(iw);
        if (str_caseend_with(output,".png"))
            AX_save_pixmap_as_png
                (iw,AX_JPG_QUALITY_TO_PNG_LEVEL(quality),output);
        else if (str_caseend_with(output,".eps"))
            AX_save_pixmap_as_eps(iw,quality,output);
        else AX_save_pixmap_as_jpg(iw,quality,output);
        frames++;
        ptr = fgets(buf,SCRIPT_LINE_SIZE,fp);
    }
    fclose(fp);
    printf ("%d frames saved.\n\n", frames);
    if (temporary_disable_bond)
    {
        Config_to_3D_Bonds (n[iw].bond_radius);
        if (n[iw].bond_mode)
        {
            bond_xtal_origin_update (iw);
            bond_atom_color_update(iw);
        }
        else
        {
            n[iw].bond_xtal_origin_need_update = TRUE;
            n[iw].bond_atom_color_need_update = TRUE;
        }
        temporary_disable_bond = 0;
    }
    return;
} /* end script_animate() */