Exemplo n.º 1
0
static void
readFromPipe (evutil_socket_t   fd,
              short             eventType,
              void            * veh)
{
    char              ch;
    int               ret;
    tr_event_handle * eh = veh;

    dbgmsg ("readFromPipe: eventType is %hd", eventType);

    /* read the command type */
    ch = '\0';
    do
    {
        ret = piperead (fd, &ch, 1);
    }
    while (!eh->die && ret < 0 && errno == EAGAIN);

    dbgmsg ("command is [%c], ret is %d, errno is %d", ch, ret, (int)errno);

    switch (ch)
    {
        case 'r': /* run in libevent thread */
        {
            struct tr_run_data data;
            const size_t       nwant = sizeof (data);
            const ev_ssize_t   ngot = piperead (fd, &data, nwant);
            if (!eh->die && (ngot == (ev_ssize_t) nwant))
            {
                dbgmsg ("invoking function in libevent thread");
              (data.func)(data.user_data);
            }
            break;
        }

        case '\0': /* eof */
        {
            dbgmsg ("pipe eof reached... removing event listener");
            event_free (eh->pipeEvent);
            tr_netCloseSocket (eh->fds[0]);
            event_base_loopexit (eh->base, NULL);
            break;
        }

        default:
        {
            assert (0 && "unhandled command type!");
            break;
        }
    }
}
Exemplo n.º 2
0
void print_msg(int flag) {
	set_signal(SIGCHAT, print_msg);
	char buf[USER_NAME_MAX_LENGTH + 10], private;
	if (flag) {
		char buf2[STR_BUF_SIZE];
		piperead(Pdesc2[1], Pdesc[0], &private, sizeof(char));
		piperead(Pdesc2[1], Pdesc[0], buf, USER_NAME_MAX_LENGTH + 10);
		piperead(Pdesc2[1], Pdesc[0], buf2, STR_BUF_SIZE);
		if (private == PRIVATE)
			wattron(chatbox, A_BOLD);
		writestr(buf);
		writestr(buf2); 
		wattroff(chatbox, A_BOLD);
	}
	else {   
// Read from file f.
int
fileread(struct file *f, char *addr, int n) {
	int r;

	if (f->readable == 0) {
		return -1;
	}

	if (f->type == FD_PIPE) {
		return piperead(f->pipe, addr, n);
	}

	if (f->type == FD_INODE) {
		ilock(f->ip);

		if ((r = readi(f->ip, addr, f->off, n)) > 0) {
			f->off += r;
		}

		iunlock(f->ip);
		return r;
	}

	panic("fileread");
}
Exemplo n.º 4
0
/*
 * read err msg from err pipe
 */
static void
read_err_msg(int fid, StringInfo sinfo)
{
	char ebuf[512];
	int ebuflen = 512;

	while (true)
	{
		int nread = piperead(fid, ebuf, ebuflen);

		if(nread == 0)
		{
			break;
		}
		else if(nread > 0)
		{
			appendBinaryStringInfo(sinfo, ebuf, nread);
		}
		else
		{
			appendStringInfoString(sinfo, "error string unavailable due to read error");
			break;
		}
	}

	if (sinfo->len > 0){
		write_log("read err msg from pipe, len:%d msg:%s", sinfo->len, sinfo->data);
	}
}
Exemplo n.º 5
0
size_t
url_execute_fread(void *ptr, size_t size, URL_FILE *file, CopyState pstate)
{
	URL_EXECUTE_FILE *efile = (URL_EXECUTE_FILE *) file;

	return piperead(efile->handle->pipes[EXEC_DATA_P], ptr, size);
}
Exemplo n.º 6
0
int wait_until_received(const int mtype) { 
    if (mtype > 0 && mtype <= MSG_TYPES_NUMBER) {
		if (pipewrite(Pdesc2[1], Pdesc[0], &mtype, sizeof(int)) == FAIL)
			return FAIL;
        if (mtype == RESPONSE) {
			if (piperead(Pdesc2[1], Pdesc[0], &response_data.response_type, sizeof(int)) == FAIL ||
			piperead(Pdesc2[1], Pdesc[0], response_data.content, RESPONSE_LENGTH) == FAIL) {
				return FAIL;
			}
        }
		else if (mtype == USERS || mtype == ROOMS || mtype == ROOM_USERS_LIST) {
			int j = 0;
			while (piperead(Pdesc2[1], Pdesc[0], request_response_data->content[j], USER_NAME_MAX_LENGTH) > FAIL)
				++j;
			if (j < MAX_SERVERS_NUMBER * MAX_USERS_NUMBER)
				request_response_data->content[j][0] = '\0';
		}
		return 0;
	}
    return FAIL;
}
Exemplo n.º 7
0
int 
yuv_read_frame (int fd, unsigned char *yuv[3], int width, int height)
{

   int v, h, i;
   unsigned char magic[7];

   if (piperead (fd, magic, 6) != 6)
      return 0;
   if (strncmp (magic, "FRAME\n", 6)) {
      magic[6] = '\0';
      printf("Error (yuv4mpeg.c): \nStart of frame is not \"FRAME\\n\"\n");
      return 0;
      /* should we return -1 and set errno = EBADMSG instead? */
   }

   h = width;
   v = height;

   /* Read luminance scanlines */

   for (i = 0; i < v; i++)
      if (piperead (fd, yuv[0] + i * h, h) != h)
         return 0;

   v /= 2;
   h /= 2;

   /* Read chrominance scanlines */

   for (i = 0; i < v; i++)
      if (piperead (fd, yuv[1] + i * h, h) != h)
         return 0;
   for (i = 0; i < v; i++)
      if (piperead (fd, yuv[2] + i * h, h) != h)
         return 0;
   return 1;
}
Exemplo n.º 8
0
int readPipe(int fd, void *buff, int buffsize)
{
	int   s   = 0;
	int	  res = 0;
retry:
	res = piperead(fd, (char *)buff + s, buffsize - s);
	if ( res > 0 ) {
		s += res;
		if ( buffsize - s > 0 ) {
			goto retry;
		}
		return s;
	}
	else if ( res == 0 ) {
		return s;
	}
	else if ( res == -1 && (errno == EAGAIN || errno == EINTR)) {
		goto retry;
	}

	write_log("readPipe got read() error , fd %d, (errno %d)", fd, errno);

	return -1;
}
Exemplo n.º 9
0
bool
url_execute_ferror(URL_FILE *file, int bytesread, char *ebuf, int ebuflen)
{
	URL_EXECUTE_FILE *efile = (URL_EXECUTE_FILE *) file;
	int			ret;
	int			nread;

	ret = (bytesread == -1);
	if(ret == true && ebuflen > 0 && ebuf != NULL)
	{
		/*
		 * Read one byte less than the maximum size to ensure zero
		 * termination of the buffer.
		 */
		nread = piperead(efile->handle->pipes[EXEC_ERR_P], ebuf, ebuflen -1);

		if(nread != -1)
			ebuf[nread] = 0;
		else
			strncpy(ebuf,"error string unavailable due to read error",ebuflen-1);
	}

	return ret;
}
Exemplo n.º 10
0
/*
 * Called in the background process whenever a complete segment of WAL
 * has been received.
 * On Unix, we check to see if there is any data on our pipe
 * (which would mean we have a stop position), and if it is, check if
 * it is time to stop.
 * On Windows, we are in a single process, so we can just check if it's
 * time to stop.
 */
static bool
segment_callback(XLogRecPtr segendpos, uint32 timeline)
{
	if (!has_xlogendptr)
	{
#ifndef WIN32
		fd_set		fds;
		struct timeval tv;
		int			r;

		/*
		 * Don't have the end pointer yet - check our pipe to see if it has
		 * been sent yet.
		 */
		FD_ZERO(&fds);
		FD_SET(bgpipe[0], &fds);

		MemSet(&tv, 0, sizeof(tv));

		r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
		if (r == 1)
		{
			char		xlogend[64];

			MemSet(xlogend, 0, sizeof(xlogend));
			r = piperead(bgpipe[0], xlogend, sizeof(xlogend));
			if (r < 0)
			{
				fprintf(stderr, _("%s: could not read from ready pipe: %s\n"),
						progname, strerror(errno));
				exit(1);
			}

			if (sscanf(xlogend, "%X/%X", &xlogendptr.xlogid, &xlogendptr.xrecoff) != 2)
			{
				fprintf(stderr, _("%s: could not parse xlog end position \"%s\"\n"),
						progname, xlogend);
				exit(1);
			}
			has_xlogendptr = 1;

			/*
			 * Fall through to check if we've reached the point further
			 * already.
			 */
		}
		else
		{
			/*
			 * No data received on the pipe means we don't know the end
			 * position yet - so just say it's not time to stop yet.
			 */
			return false;
		}
#else

		/*
		 * On win32, has_xlogendptr is set by the main thread, so if it's not
		 * set here, we just go back and wait until it shows up.
		 */
		return false;
#endif
	}

	/*
	 * At this point we have an end pointer, so compare it to the current
	 * position to figure out if it's time to stop.
	 */
	if (segendpos.xlogid > xlogendptr.xlogid ||
		(segendpos.xlogid == xlogendptr.xlogid &&
		 segendpos.xrecoff >= xlogendptr.xrecoff))
		return true;

	/*
	 * Have end pointer, but haven't reached it yet - so tell the caller to
	 * keep streaming.
	 */
	return false;
}
Exemplo n.º 11
0
/*
 * Main entry point for syslogger process
 * argc/argv parameters are valid only in EXEC_BACKEND case.
 */
__noexec_static__ void syslog_main(int argc, char *argv[])
{
#ifndef WIN32
	char logbuffer[READ_BUF_SIZE];
	int bytes_in_logbuffer = 0;
#endif

	char *current_log_dir;
	char *current_log_fname;
	int current_log_rotation_age;

	child = true;/* we are a postmaster subprocess now */
	current_pid = getpid();	/* reset current_pid */
	proc_start_time = time(NULL);/* set our start time in case we call elog */

#ifdef EXEC_BACKEND
	syslogger_parse_args(argc, argv);
#endif   /* EXEC_BACKEND */

	am_syslogger = true;
	init_ps_display("logger process", "", "", "");

	/*
	 * If we restarted, our stderr is already redirected into our own input
	 * pipe.  This is of course pretty useless, not to mention that it
	 * interferes with detecting pipe EOF.	Point stderr to /dev/null. This
	 * assumes that all interesting messages generated in the syslogger will
	 * come through elog.c and will be sent to write_syslogger.
	 */
	if (redirection_done) {
		int fd = open(DEVNULL, O_WRONLY, 0);

		/*
		 * The closes might look redundant, but they are not. We want 
		 * to be sure the pipe gets closed even if the open failed.
		 * We can survive running with stderr pointing nowhere, but we 
		 * can't afford to have extra pipe input descriptors hanging i
		 * around.
		 */
		close(fileno(stdout));
		close(fileno(stderr));
		if (fd != -1) {
			dup2(fd, fileno(stdout));
			dup2(fd, fileno(stderr));
			close(fd);
		}
	}

	/*
	 * Syslogger's own stderr can't be the syslog_pipe, so set it back to i
	 * text mode if we didn't just close it. It was set to binary in
	 * submaster_main.
	 */
#ifdef WIN32
	else {
		_setmode(_fileno(stderr), _O_TEXT);
	}
#endif

	/*
	 * Also close our copy of the write end of the pipe.  This is needed to
	 * ensure we can detect pipe EOF correctly. But note that in the restart
	 * case, the postmaster already did this.
	 */
#ifndef WIN32
	if (syslog_pipe[1] >= 0)
		close(syslog_pipe[1]);

	syslog_pipe[1] = -1;
#else
	if (syslog_pipe[1])
		CloseHandle(syslog_pipe[1]);

	syslog_pipe[1] = 0;
#endif

	/*
	 * If possible, make this process a group leader, so that the postmaster
	 * can signal any child processes too. Syslogger probably never has any
	 * child processes, but for consistency we make all postmaster child
	 * processes do this.
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif

	/*
	 * Properly accept or ignore signals the postmaster might send us
	 * We ignore all termination signals, and instead exit only when all
	 * upstream processes are gone, to ensure we don't miss any dying gaspsi
	 * of broken backends...
	 */
	pqsignal(SIGHUP, syslog_sighup_handler); 	/* set flag to read conf file */
	pqsignal(SIGINT, SIG_IGN);
	pqsignal(SIGTERM, SIG_IGN);
	pqsignal(SIGQUIT, SIG_IGN);
	pqsignal(SIGALRM, SIG_IGN);
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, syslog_sigusr1_handler);	/* request log rotation */
	pqsignal(SIGUSR2, SIG_IGN);

	/*
	 * Reset some signals that are accepted by postmaster but not here
	 */
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);

	SIGSET_MASK(&unblock_signal);

#ifdef WIN32
	/* Fire up separate data transfer thread */
	InitializeCriticalSection(&sysloggerSection);
	EnterCriticalSection(&sysloggerSection);

	threadHandle = (HANDLE) _beginthreadex(NULL, 0, pipeThread, NULL, 0, NULL);
	if (threadHandle == 0)
		elog(FATAL, "could not create syslogger thread: %m");
#endif   /* WIN32 */

	/* 
	 * Remember active logfile parameters
	 */
	current_log_dir = pstrdup(log_directory);
	current_log_fname = pstrdup(log_filename);
	current_log_rotation_age = log_rotation_age;

	/* 
	 * Set next planned rotation time
	 */
	set_next_rotation_time();

	/* 
	 * Main worker loop
	 */
	for (;;) {
		bool time_based_rotation = false;
		int size_rotation_for = 0;
#ifndef WIN32
		int bytesRead;
		int rc;
		fd_set rfds;
		struct timeval timeout;
#endif

		if (got_sighup) {
			got_sighup = false;
			process_config_file(PGC_SIGHUP);

			/*
			 * Check if the log directory or filename pattern 
			 * changed in postgresql.conf. If so, force rotation to
			 * make sure we're writing the logfiles in the right
			 * place.
			 */
			if (strcmp(log_directory, current_log_dir) != 0) {
				pfree(current_log_dir);
				current_log_dir = pstrdup(log_directory);
				rotation_requested = true;
			}

			if (strcmp(log_filename, current_log_fname) != 0) {
				pfree(current_log_fname);
				current_log_fname = pstrdup(log_filename);
				rotation_requested = true;
			}

			/*
			 * If rotation time parameter changed, reset next 
			 * rotation time, but don't immediately force aa 
			 * rotation.
			 */
			if (current_log_rotation_age != log_rotation_age) {
				current_log_rotation_age = log_rotation_age;
				set_next_rotation_time();
			}
		}

		if (!rotation_requested && log_rotation_age > 0) {
			/* Do a logfile rotation if it's time */
			pg_time_t now = (pg_time_t) time(NULL);
			if (now >= next_rotation_time)
				rotation_requested = time_based_rotation = true;
		}

		if (!rotation_requested && log_rotation_size > 0) {
			/* 
			 * Do a rotation if file is too big
			 */
			if (ftell(syslog_file) >= log_rotation_size * 1024L) {
				rotation_requested = true;
				size_rotation_for |= DEST_STDERR;
			}

			if (cvs_logfile != NULL
				&& ftell(cvs_logfile) >= log_rotation_size * 1024L) {
				rotation_requested = true;
				size_rotation_for |= DEST_CSVLOG;
			}
		}

		if (rotation_requested) {
			/*
			 * Force rotation when both values are zero. It means 
			 * the request was sent by pg_rotate_logfile.
			 */
			if (!time_based_rotation && size_rotation_for == 0)
				size_rotation_for = DEST_STDERR | DEST_CSVLOG;

			logfile_rotate(time_based_rotation, size_rotation_for);
		}

#ifndef WIN32

		/*
		 * Wait for some data, timing out after 1 second
		 */
		FD_ZERO(&rfds);
		FD_SET(syslog_pipe[0], &rfds);
		timeout.tv_sec = 1;
		timeout.tv_usec = 0;
		rc = select(syslog_pipe[0] + 1, &rfds, NULL, NULL, &timeout);

		if (rc < 0) {
			if (errno != EINTR) {
				ereport(LOG, (
				errcode_sock_access(),
				errmsg("select() failed in logger process: %m")));
			}
		} else if (rc > 0 && FD_ISSET(syslog_pipe[0], &rfds)) {
			bytesRead = piperead(
				syslog_pipe[0],
				logbuffer + bytes_in_logbuffer,
				sizeof(logbuffer) - bytes_in_logbuffer);
			if (bytesRead < 0) {
				if (errno != EINTR)
					ereport(LOG, (errcode_sock_access(),
					errmsg("could not read from logger pipe: %m")));
			} else if (bytesRead > 0) {
				bytes_in_logbuffer += bytesRead;
				process_pipe_input(logbuffer, &bytes_in_logbuffer);
				continue;
			} else {
				/*
				 * Zero bytes read when select() is saying 
				 * read-ready means EOF on the pipe. That is,
				 * there are no longer any processes with the
				 * pipe write end open. Therefore, the PM and
				 * all backends are shut down, and we are done.
				 */
				pipe_eof_seen = true;

				/* 
				 * If there's any data left then force it out 
				 * now
				 */
				flush_pipe_input(logbuffer, &bytes_in_logbuffer);
			}
		}
#else					/* WIN32 */

		/*
		 * On Windows we leave it to a separate thread to transfer data
		 * and detect pipe EOF. The main thread just wakes up once a
		 * second to check for SIGHUP and rotation conditions.
		 *
		 * Server code isn't generally thread-safe, so we ensure that 
		 * only one of the threads is active at a time by entering the
		 * critical section whenever we're not sleeping.
		 */
		LeaveCriticalSection(&sysloggerSection);
		pg_usleep(1000000L);
		EnterCriticalSection(&sysloggerSection);
#endif   /* WIN32 */

		if (pipe_eof_seen) {
			/*
			 * Seeing this message on the real stderr is annoying.
			 * So we make it DEBUG1 to suppress in normal use.
			 */
			ereport(DEBUG1, (errmsg("logger shutting down")));

			/*
			 * Normal exit from the syslogger is here. Note that we
			 * deliberately do not close syslog_file before exiting.
			 * This is to allow for the possibility of elog 
			 * messages being generated inside proc_exit. Regular
			 * exit() will take care of flushing and closing stdio
			 * channels.
			 */
			proc_exit(0);
		}
	}
}
Exemplo n.º 12
0
static void
readFromPipe( int    fd,
              short  eventType,
              void * veh )
{
    char              ch;
    int               ret;
    tr_event_handle * eh = veh;

    dbgmsg( "readFromPipe: eventType is %hd", eventType );

    /* read the command type */
    ch = '\0';
    do
    {
        ret = piperead( fd, &ch, 1 );
    }
    while( !eh->die && ret < 0 && errno == EAGAIN );

    dbgmsg( "command is [%c], ret is %d, errno is %d", ch, ret, (int)errno );

    switch( ch )
    {
        case 'r': /* run in libevent thread */
        {
            struct tr_run_data data;
            const size_t       nwant = sizeof( data );
            const ssize_t      ngot = piperead( fd, &data, nwant );
            if( !eh->die && ( ngot == (ssize_t)nwant ) )
            {
                dbgmsg( "invoking function in libevent thread" );
                ( data.func )( data.user_data );
            }
            break;
        }

        case 't': /* create timer */
        {
            tr_timer *    timer;
            const size_t  nwant = sizeof( timer );
            const ssize_t ngot = piperead( fd, &timer, nwant );
            if( !eh->die && ( ngot == (ssize_t)nwant ) )
            {
                dbgmsg( "adding timer in libevent thread" );
                evtimer_add( &timer->event, &timer->tv );
            }
            break;
        }

        case '\0': /* eof */
        {
            dbgmsg( "pipe eof reached... removing event listener" );
            event_del( &eh->pipeEvent );
            break;
        }

        default:
        {
            assert( 0 && "unhandled command type!" );
            break;
        }
    }
}
Exemplo n.º 13
0
static gboolean
client_thread_loop (BlockTxClient *client)
{
    BlockTxInfo *info = client->info;
    fd_set fds;
    int max_fd = MAX (info->cmd_pipe[0], client->data_fd);
    int rc;
    gboolean restart = FALSE;
    struct timeval tmo;

    while (1) {
        FD_ZERO (&fds);
        FD_SET (info->cmd_pipe[0], &fds);

        /* Stop receiving any data after the client was shutdown. */
        if (client->recv_state != RECV_STATE_DONE) {
            FD_SET (client->data_fd, &fds);
            max_fd = MAX (info->cmd_pipe[0], client->data_fd);
        } else
            max_fd = info->cmd_pipe[0];

        /* If the client is already shutdown, no need to add timeout. */
        if (client->recv_state != RECV_STATE_DONE) {
            tmo.tv_sec = RECV_TIMEOUT_SEC;
            tmo.tv_usec = 0;
            rc = select (max_fd + 1, &fds, NULL, NULL, &tmo);
        } else {
            rc = select (max_fd + 1, &fds, NULL, NULL, NULL);
        }

        if (rc < 0 && errno == EINTR) {
            continue;
        } else if (rc < 0) {
            seaf_warning ("select error: %s.\n", strerror(errno));
            client->info->result = BLOCK_CLIENT_FAILED;
            break;
        } else if (rc == 0) {
            /* timeout */
            if (info->task->type == TASK_TYPE_DOWNLOAD) {
                seaf_warning ("Recv timeout.\n");
                client->info->result = BLOCK_CLIENT_NET_ERROR;
                if (do_break_loop (client))
                    break;
            }
            continue;
        }

        if (client->recv_state != RECV_STATE_DONE &&
            FD_ISSET (client->data_fd, &fds)) {
            recv_data_cb (client);
            if (client->break_loop && do_break_loop (client))
                break;
        }

        if (FD_ISSET (info->cmd_pipe[0], &fds)) {
            int cmd;
            piperead (info->cmd_pipe[0], &cmd, sizeof(int));

            if (cmd == BLOCK_CLIENT_CMD_RESTART) {
                restart = TRUE;
                break;
            }

            if (handle_command (client, cmd))
                break;
        }
    }

    return restart;
}
Exemplo n.º 14
0
/*
 * Main entry point for syslogger process
 * argc/argv parameters are valid only in EXEC_BACKEND case.
 */
NON_EXEC_STATIC void
SysLoggerMain(int argc, char *argv[])
{
	char	   *currentLogDir;
	char	   *currentLogFilename;
	int			currentLogRotationAge;

	IsUnderPostmaster = true;	/* we are a postmaster subprocess now */

	MyProcPid = getpid();		/* reset MyProcPid */

	/* Lose the postmaster's on-exit routines */
	on_exit_reset();

#ifdef EXEC_BACKEND
	syslogger_parseArgs(argc, argv);
#endif   /* EXEC_BACKEND */

	am_syslogger = true;

	init_ps_display("logger process", "", "");
	set_ps_display("");

	/*
	 * If we restarted, our stderr is already redirected into our own
	 * input pipe.	This is of course pretty useless, not to mention that
	 * it interferes with detecting pipe EOF.  Point stderr to /dev/null.
	 * This assumes that all interesting messages generated in the
	 * syslogger will come through elog.c and will be sent to
	 * write_syslogger_file.
	 */
	if (redirection_done)
	{
		int			fd = open(NULL_DEV, O_WRONLY);

		/*
		 * The closes might look redundant, but they are not: we want to
		 * be darn sure the pipe gets closed even if the open failed.  We
		 * can survive running with stderr pointing nowhere, but we can't
		 * afford to have extra pipe input descriptors hanging around.
		 */
		close(fileno(stdout));
		close(fileno(stderr));
		dup2(fd, fileno(stdout));
		dup2(fd, fileno(stderr));
		close(fd);
	}

	/*
	 * Also close our copy of the write end of the pipe.  This is needed
	 * to ensure we can detect pipe EOF correctly.	(But note that in the
	 * restart case, the postmaster already did this.)
	 */
#ifndef WIN32
	if (syslogPipe[1] >= 0)
		close(syslogPipe[1]);
	syslogPipe[1] = -1;
#else
	if (syslogPipe[1])
		CloseHandle(syslogPipe[1]);
	syslogPipe[1] = 0;
#endif

	/*
	 * Properly accept or ignore signals the postmaster might send us
	 *
	 * Note: we ignore all termination signals, and instead exit only when
	 * all upstream processes are gone, to ensure we don't miss any dying
	 * gasps of broken backends...
	 */

	pqsignal(SIGHUP, sigHupHandler);	/* set flag to read config file */
	pqsignal(SIGINT, SIG_IGN);
	pqsignal(SIGTERM, SIG_IGN);
	pqsignal(SIGQUIT, SIG_IGN);
	pqsignal(SIGALRM, SIG_IGN);
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, SIG_IGN);
	pqsignal(SIGUSR2, SIG_IGN);

	/*
	 * Reset some signals that are accepted by postmaster but not here
	 */
	pqsignal(SIGCHLD, SIG_DFL);
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);
	pqsignal(SIGWINCH, SIG_DFL);

	PG_SETMASK(&UnBlockSig);

#ifdef WIN32
	/* Fire up separate data transfer thread */
	InitializeCriticalSection(&sysfileSection);

	{
		unsigned int tid;

		threadHandle = (HANDLE) _beginthreadex(0, 0, pipeThread, 0, 0, &tid);
	}
#endif   /* WIN32 */

	/* remember active logfile parameters */
	currentLogDir = pstrdup(Log_directory);
	currentLogFilename = pstrdup(Log_filename);
	currentLogRotationAge = Log_RotationAge;
	/* set next planned rotation time */
	set_next_rotation_time();

	/* main worker loop */
	for (;;)
	{
		bool		rotation_requested = false;
		bool		time_based_rotation = false;

#ifndef WIN32
		char		logbuffer[1024];
		int			bytesRead;
		int			rc;
		fd_set		rfds;
		struct timeval timeout;
#endif

		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);

			/*
			 * Check if the log directory or filename pattern changed in 
			 * postgresql.conf. If so, force rotation to make sure we're 
			 * writing the logfiles in the right place.
			 */
			if (strcmp(Log_directory, currentLogDir) != 0)
			{
				pfree(currentLogDir);
				currentLogDir = pstrdup(Log_directory);
				rotation_requested = true;
			}
			if (strcmp(Log_filename, currentLogFilename) != 0)
			{
				pfree(currentLogFilename);
				currentLogFilename = pstrdup(Log_filename);
				rotation_requested = true;
			}
			/*
			 * If rotation time parameter changed, reset next rotation time,
			 * but don't immediately force a rotation.
			 */
			if (currentLogRotationAge != Log_RotationAge)
			{
				currentLogRotationAge = Log_RotationAge;
				set_next_rotation_time();
			}
		}

		if (!rotation_requested && Log_RotationAge > 0)
		{
			/* Do a logfile rotation if it's time */
			pg_time_t	now = time(NULL);

			if (now >= next_rotation_time)
				rotation_requested = time_based_rotation = true;
		}

		if (!rotation_requested && Log_RotationSize > 0)
		{
			/* Do a rotation if file is too big */
			if (ftell(syslogFile) >= Log_RotationSize * 1024L)
				rotation_requested = true;
		}

		if (rotation_requested)
			logfile_rotate(time_based_rotation);

#ifndef WIN32

		/*
		 * Wait for some data, timing out after 1 second
		 */
		FD_ZERO(&rfds);
		FD_SET(syslogPipe[0], &rfds);
		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		rc = select(syslogPipe[0] + 1, &rfds, NULL, NULL, &timeout);

		if (rc < 0)
		{
			if (errno != EINTR)
				ereport(LOG,
						(errcode_for_socket_access(),
					   errmsg("select() failed in logger process: %m")));
		}
		else if (rc > 0 && FD_ISSET(syslogPipe[0], &rfds))
		{
			bytesRead = piperead(syslogPipe[0],
								 logbuffer, sizeof(logbuffer));

			if (bytesRead < 0)
			{
				if (errno != EINTR)
					ereport(LOG,
							(errcode_for_socket_access(),
						 errmsg("could not read from logger pipe: %m")));
			}
			else if (bytesRead > 0)
			{
				write_syslogger_file_binary(logbuffer, bytesRead);
				continue;
			}
			else
			{
				/*
				 * Zero bytes read when select() is saying read-ready
				 * means EOF on the pipe: that is, there are no longer any
				 * processes with the pipe write end open.	Therefore, the
				 * postmaster and all backends are shut down, and we are
				 * done.
				 */
				pipe_eof_seen = true;
			}
		}
#else							/* WIN32 */

		/*
		 * On Windows we leave it to a separate thread to transfer data
		 * and detect pipe EOF.  The main thread just wakes up once a
		 * second to check for SIGHUP and rotation conditions.
		 */
		pgwin32_backend_usleep(1000000);
#endif   /* WIN32 */

		if (pipe_eof_seen)
		{
			ereport(LOG,
					(errmsg("logger shutting down")));

			/*
			 * Normal exit from the syslogger is here.	Note that we
			 * deliberately do not close syslogFile before exiting; this
			 * is to allow for the possibility of elog messages being
			 * generated inside proc_exit.	Regular exit() will take care
			 * of flushing and closing stdio channels.
			 */
			proc_exit(0);
		}
	}
}
Exemplo n.º 15
0
Arquivo: zone.c Projeto: velour/mid
static FILE *zpipe(Rng *r, int depth)
{
	Pipe p = {};

	switch(depth){
	case 0:
		pipeadd(&p, "lvlgen", "25 25 3 -s %lu ", (unsigned long) rngint(r));
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemStatup);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d %d %d %d 50", (unsigned long) rngint(r),
			ItemCopper, ItemCopper, ItemCopper, ItemCopper, ItemCopper, 
			ItemSilver, ItemSilver,
			ItemGold
		);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d 5", (unsigned long) rngint(r),
			ItemHealth, ItemHealth, ItemHealth, ItemHealth,
			ItemCarrot
		);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d 1", (unsigned long) rngint(r),
			ItemBubble, ItemZap, ItemLead
		);
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemHamCan);
		pipeadd(&p, "envgen", "-s %lu %d 1", (unsigned long) rngint(r), EnvShrempty);
		pipeadd(&p, "envgen", "-s %lu %d %d %d 2", (unsigned long) rngint(r),
			EnvSwdStoneHp,
			EnvSwdStoneDex,
			EnvSwdStoneStr);
		pipeadd(&p, "envgen", "-s %lu %d %d %d %d 2", (unsigned long)rngint(r),
			EnvHelm0,
			EnvBody0,
			EnvGlove0,
			EnvBoot0);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d %d %d %d %d %d %d %d 50",
			(unsigned long) rngint(r),
			EnemyUnti, EnemyUnti, EnemyUnti,
			EnemyNous, EnemyNous, EnemyNous, EnemyNous,
			EnemyDa, EnemyDa, EnemyDa,
			EnemyThu,
			EnemyGrendu
		);
		break;
	case 1:
		pipeadd(&p, "lvlgen", "25 25 3 -s %lu ", (unsigned long) rngint(r));
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemStatup);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d %d %d %d 50", (unsigned long) rngint(r),
			ItemCopper, ItemCopper, ItemCopper, ItemCopper, 
			ItemSilver, ItemSilver, ItemSilver,
			ItemGold
		);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d 5", (unsigned long) rngint(r),
			ItemHealth, ItemHealth, ItemHealth,
			ItemCarrot, ItemCarrot
		);
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemHamCan);
		pipeadd(&p, "envgen", "-s %lu %d 1", (unsigned long) rngint(r), EnvShrempty);
		pipeadd(&p, "envgen", "-s %lu %d %d %d 2", (unsigned long) rngint(r),
			EnvSwdStoneHp,
			EnvSwdStoneDex,
			EnvSwdStoneStr);
		pipeadd(&p, "envgen", "-s %lu %d %d %d %d 2", (unsigned long)rngint(r),
			EnvHelm0,
			EnvBody0,
			EnvGlove0,
			EnvBoot0);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d %d %d %d %d %d %d %d 50",
			(unsigned long) rngint(r),
			EnemyUnti, EnemyUnti, EnemyUnti,
			EnemyNous, EnemyNous, EnemyNous,
			EnemyDa, EnemyDa, EnemyDa,
			EnemyThu, EnemyThu,
			EnemyGrendu
		);
		break;
	case 2:
		pipeadd(&p, "lvlgen", "25 25 3 -s %lu ", (unsigned long) rngint(r));
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemStatup);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d %d %d %d 50", (unsigned long) rngint(r),
			ItemCopper, ItemCopper, ItemCopper, 
			ItemSilver, ItemSilver, ItemSilver, ItemSilver,
			ItemGold
		);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d 5", (unsigned long) rngint(r),
			ItemHealth, ItemHealth,
			ItemCarrot, ItemCarrot, ItemCarrot
		);
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemHamCan);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d 1", (unsigned long) rngint(r),
			ItemBubble, ItemZap, ItemLead
		);
		pipeadd(&p, "envgen", "-s %lu %d 1", (unsigned long) rngint(r), EnvShrempty);
		pipeadd(&p, "envgen", "-s %lu %d %d %d 2", (unsigned long) rngint(r),
			EnvSwdStoneHp2,
			EnvSwdStoneDex2,
			EnvSwdStoneStr2);
		pipeadd(&p, "envgen", "-s %lu %d %d %d %d 2", (unsigned long)rngint(r),
			EnvHelm2,
			EnvBody2,
			EnvGlove2,
			EnvBoot2);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d %d %d %d %d %d %d %d 50",
			(unsigned long) rngint(r),
			EnemyUnti, EnemyUnti, EnemyUnti,
			EnemyNous, EnemyNous,
			EnemyDa, EnemyDa, EnemyDa,
			EnemyThu, EnemyThu,
			EnemyGrendu, EnemyGrendu
		);
		break;
	case 3:
		pipeadd(&p, "lvlgen", "30 30 3 -s %lu ", (unsigned long) rngint(r));
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemStatup);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d %d %d %d 50", (unsigned long) rngint(r),
			ItemCopper, 
			ItemSilver, ItemSilver, ItemSilver,
			ItemGold, ItemGold, ItemGold, ItemGold
		);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d 4", (unsigned long) rngint(r),
			ItemHealth, ItemHealth,
			ItemCarrot, ItemCarrot
		);
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemHamCan);
		pipeadd(&p, "envgen", "-s %lu %d 1", (unsigned long) rngint(r), EnvShrempty);
		pipeadd(&p, "envgen", "-s %lu %d %d %d 2", (unsigned long) rngint(r),
			EnvSwdStoneHp2,
			EnvSwdStoneDex2,
			EnvSwdStoneStr2);
		pipeadd(&p, "envgen", "-s %lu %d %d %d %d 2", (unsigned long)rngint(r),
			EnvHelm2,
			EnvBody2,
			EnvGlove2,
			EnvBoot2);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d %d %d %d %d %d %d %d 25",
			(unsigned long) rngint(r),
			EnemyUnti, EnemyUnti, EnemyUnti,
			EnemyNous, EnemyNous,
			EnemyDa, EnemyDa, EnemyDa,
			EnemyThu, EnemyThu,
			EnemyGrendu, EnemyGrendu
		);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d 25",
			(unsigned long) rngint(r),
			EnemyThu, EnemyThu,
			EnemyGrendu
		);
		break;
	case 4:
		pipeadd(&p, "lvlgen", "30 30 4 -s %lu ", (unsigned long) rngint(r));
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemStatup);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d %d %d %d 50", (unsigned long) rngint(r),
			ItemCopper, 
			ItemSilver, ItemSilver, ItemSilver,
			ItemGold, ItemGold, ItemGold, ItemGold
		);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d 2", (unsigned long) rngint(r),
			ItemHealth,
			ItemCarrot
		);
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemHamCan);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d 1", (unsigned long) rngint(r),
			ItemBubble, ItemZap, ItemLead
		);
		pipeadd(&p, "envgen", "-s %lu %d 1", (unsigned long) rngint(r), EnvShrempty);
		pipeadd(&p, "envgen", "-s %lu %d %d %d 2", (unsigned long) rngint(r),
			EnvSwdStoneHp3,
			EnvSwdStoneDex3,
			EnvSwdStoneStr3);
		pipeadd(&p, "envgen", "-s %lu %d %d %d %d 2", (unsigned long)rngint(r),
			EnvHelm4,
			EnvBody4,
			EnvGlove4,
			EnvBoot4);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d %d %d %d %d %d %d %d 20",
			(unsigned long) rngint(r),
			EnemyUnti, EnemyUnti, EnemyUnti,
			EnemyNous, EnemyNous,
			EnemyDa, EnemyDa, EnemyDa,
			EnemyThu, EnemyThu,
			EnemyGrendu, EnemyGrendu
		);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d 30",
			(unsigned long) rngint(r),
			EnemyThu, EnemyThu,
			EnemyGrendu, EnemyGrendu,
			EnemyTihgt
		);
		break;
	default:
		pipeadd(&p, "lvlgen", "30 30 4 -x -s %lu ", (unsigned long) rngint(r));
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemStatup);
		pipeadd(&p, "itmgen", "-s %lu %d %d %d %d %d %d %d %d 50", (unsigned long) rngint(r),
			ItemSilver,
			ItemGold
		);
		pipeadd(&p, "itmgen", "-s %lu %d 1", (unsigned long) rngint(r), ItemHamCan);
		pipeadd(&p, "envgen", "-s %lu %d 1", (unsigned long) rngint(r), EnvShrempty);
		pipeadd(&p, "envgen", "-s %lu %d %d %d 2", (unsigned long) rngint(r),
			EnvSwdStoneHp3,
			EnvSwdStoneDex3,
			EnvSwdStoneStr3);
		pipeadd(&p, "envgen", "-s %lu %d %d %d %d 2", (unsigned long)rngint(r),
			EnvHelm4,
			EnvBody4,
			EnvGlove4,
			EnvBoot4);
		pipeadd(&p, "enmgen", "-s %lu %d %d %d %d %d %d %d %d %d %d %d %d 20",
			(unsigned long) rngint(r),
			EnemyUnti, EnemyUnti, EnemyUnti,
			EnemyNous, EnemyNous,
			EnemyDa, EnemyDa, EnemyDa,
			EnemyThu, EnemyThu,
			EnemyGrendu, EnemyGrendu
		);
		pipeadd(&p, "enmgen", "-s %lu %d 15",
			(unsigned long) rngint(r),
			EnemyTihgt
		);
		pipeadd(&p, "enmgen", "-s %lu %d 1",
			(unsigned long) rngint(r),
			EnemyHeart
		);
		break;
	}

	char adc[256];
	if(snprintf(adc, sizeof(adc), "\"%s/cur.lvl\"", zonedir) == -1)
		die("Failed to create cur.lvl path: %s", miderrstr());
	pipeadd(&p, "tee", adc);

	p.cmd[p.n - 3] = 0;

	pr("lvlgen pipeline: [%s]", p.cmd);

	FILE *fin = piperead(p.cmd);
	if (!fin)
		die("Unable to execute zone gen pipeline: %s", miderrstr());

	return fin;
}
Exemplo n.º 16
0
Arquivo: pty.c Projeto: aunali1/exopc
static int
pty_read(struct file *filp, char *buffer, int nbyte, int blocking) {
  struct pty *pty;
  struct pipe *pipeb;
#if 0
  int  final = 0,len;
#else
  int total;
#endif
  int foundnl,master;

  demand(filp, bogus filp);
  DPRINTF(CLU_LEVEL,
	  ("pty_read: filp: %08x offset: %qd nbyte: %d\n",
	   (int)filp, filp->f_pos, nbyte));
  pty = GETPTYP(filp);
				/*   lock_pty(pty); */
  master = filp->f_pos;
  demand (master == 1 || master == 0,master flag set improperly);

  pipeb = &(pty->pipe[master]);

  if (!(PTY_BUSY(1 - master,pty)) && pipeb->length == PTY_BUFFER_SIZE) {
      /* someone closed the other end, and nothing to read */
      return 0;
  }

  if (pipeb->length == PTY_BUFFER_SIZE && CHECKNB(filp)) {
    errno = EWOULDBLOCK;
    return -1;
  }
    

  while(pipeb->length == PTY_BUFFER_SIZE) {
      /* we block if cant read anything */
      unlock_filp(filp);
      wk_waitfor_value_lt (&pipeb->length, PTY_BUFFER_SIZE, 0);
#if 0
      yield(-1);
#endif
      lock_filp(filp);
  }

  if (!(PTY_BUSY(1 - master,pty)) && pipeb->length == PTY_BUFFER_SIZE) {
      /* someone closed the other end, and nothing to read */
      return 0;
  }
  
  lock_pipepty(pipeb); 

  if (master) {
      /* master pty does not have line discipline */
      total = piperead(pipeb,buffer,nbyte,0,&foundnl);
  } else {
      /* slave pty have line discipline */
      total = piperead(pipeb,buffer,nbyte,1,&foundnl);
  }
  unlock_pipepty(pipeb); 
				/*   unlock_pty(pty); */
				/*   if (master) pr_ptyp(pty);   */
  return total;
}