Ejemplo n.º 1
0
Archivo: main.c Proyecto: h2oota/Gauche
static int init_console(void)
{
#  if defined(GAUCHE_WINDOWS_NOCONSOLE)
    char buf[100];
    int in_fd, out_fd;
#define ERR(msg) do {sprintf(buf, msg, strerror(errno));goto fail;} while(0)

    if ((in_fd = open("NUL", O_RDONLY)) < 0) ERR("couldn't open NUL: %s");
    if ((out_fd = open("NUL", O_WRONLY))< 0) ERR("couldn't open NUL: %s");
    if (_dup2(in_fd, 0) < 0)  ERR("dup2(0) failed (%s)");
    if (_dup2(out_fd, 1) < 0) ERR("dup2(1) failed (%s)");
    if (_dup2(out_fd, 2) < 0) ERR("dup2(2) failed (%s)");
    close(in_fd);
    close(out_fd);
    return FALSE;
#undef ERR
 fail:
    MessageBoxA(NULL, buf, "gosh-noconsole", MB_OK|MB_ICONERROR);
    Scm_Exit(1);
#  else /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
    /* This saves so much trouble */
    _setmode(_fileno(stdin),  _O_BINARY);
    _setmode(_fileno(stdout), _O_BINARY);
    _setmode(_fileno(stderr), _O_BINARY);
    return TRUE;
#  endif /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
}
Ejemplo n.º 2
0
static int init_console(void)
{
#  if defined(GAUCHE_WINDOWS_NOCONSOLE)
    char buf[100];
    int in_fd, out_fd;
#define ERR(msg) do {sprintf(buf, msg, strerror(errno));goto fail;} while(0)
    /* If we don't have console, we'll start off with stdio to be redirected
       to NUL; but whenever Scheme program tries to do I/O from/to
       standard Scheme ports, we open the console and reconnect the
       ports. */
    if ((in_fd  = open("NUL", O_RDONLY)) < 0) ERR("couldn't open NUL: %s");
    if ((out_fd = open("NUL", O_WRONLY)) < 0) ERR("couldn't open NUL: %s");
    if (_dup2(in_fd,  0) < 0) ERR("dup2(0) failed (%s)");
    if (_dup2(out_fd, 1) < 0) ERR("dup2(1) failed (%s)");
    if (_dup2(out_fd, 2) < 0) ERR("dup2(2) failed (%s)");
    close(in_fd);
    close(out_fd);
    return FALSE;
#undef ERR
fail:
    MessageBoxA(NULL, buf, "gosh-noconsole", MB_OK|MB_ICONERROR);
    Scm_Exit(1);
#  else /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
    /* This saves so much trouble */
    _setmode(_fileno(stdin),  _O_BINARY);
    _setmode(_fileno(stdout), _O_BINARY);
    _setmode(_fileno(stderr), _O_BINARY);
    return TRUE;
#  endif /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
}
Ejemplo n.º 3
0
static void init_dbgfp()
{
#if _DBG
	if (!dbgfp) {
#if (!HIME_IME || 1) && !CONSOLE_OFF
		AllocConsole();
		fclose(stdout);
		fclose(stderr);
		int fh = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0);
		_dup2(fh, 1);
		_dup2(fh, 2);
		_fdopen(1, "wt");
		_fdopen(2, "wt");
		fflush(stdout);
#endif
		char tt[512];
#if HIME_IME
		sprintf(tt, "C:\\dbg\\ime%x", GetCurrentProcessId());
#elif HIME_SVR
		sprintf(tt, "C:\\dbg\\svr%x", GetCurrentProcessId());
#else
		sprintf(tt, "C:\\dbg\\other%x", GetCurrentProcessId());
#endif
		dbgfp=_fsopen(tt, "wt",  _SH_DENYWR);
		setbuf(dbgfp, NULL);

		char exe[MAX_PATH];
		GetModuleFileNameA(NULL, exe, sizeof(exe));
		dbg("started %s\n", exe);
	}
#endif
}
Ejemplo n.º 4
0
int main(int ac, char **av)
{
  int  savo, savi;
  FILE *fnul;
  char name[256];
  char fullname[256];
  char *p;

  kpse_set_program_name(av[0], "mkocp");

  if(ac != 2) {
    fprintf(stderr,"%s : Usage %s ocpname\n", av[0], av[0]);
    return 1;
  }

  p = strrchr(av[1], '.');
  if(p)
    *p = '\0';
  strcpy(name, av[1]);
  strcpy(fullname, name);
  strcat(fullname, ".ocp");

/* save stdout and stdin */
  savo = _dup(fileno(stdout));
  savi = _dup(fileno(stdin));

/* connect stdout to stderr */
  _dup2(fileno(stderr), fileno(stdout));

/* connect stdin to nul device */
  if(!(fnul = fopen("nul", "r"))) {
    fprintf(stderr, "Cannot open nul device to read\n");
    exit(100);
  }
  _dup2(fileno(fnul), fileno(stdin));

/* COMMAND */

  _spawnlp(_P_WAIT, "otp2ocp", "otp2ocp", name, NULL);

/* END COMMAND */
  
/* return to original stdout and stdin */
  _dup2(savo, fileno(stdout));
  close(savo);
  _dup2(savi, fileno(stdin));
  close(savi);

/* close nul device */
  fclose(fnul);

  if(_access(fullname, 0) == 0)
    printf("%s\n", fullname);

  return 0;
}
Ejemplo n.º 5
0
int main(int argc, char **argv)
#endif /* __APPLE__ */
{
	bool commit_dune_cfg = false;
#if defined(_WIN32)
	#if defined(__MINGW32__) && defined(__STRICT_ANSI__)
		int __cdecl __MINGW_NOTHROW _fileno (FILE*);
	#endif
	FILE *err = fopen("error.log", "w");
	FILE *out = fopen("output.log", "w");

	#if defined(_MSC_VER)
		_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
	#endif

	if (err != NULL) _dup2(_fileno(err), _fileno(stderr));
	if (out != NULL) _dup2(_fileno(out), _fileno(stdout));
	FreeConsole();
#endif
	CrashLog_Init();

	VARIABLE_NOT_USED(argc);
	VARIABLE_NOT_USED(argv);

	if (!File_Init()) {
		Error("Cannot initialise files. Does %s directory exist ?\n", DATA_DIR);
		exit(1);
	}

	/* Loading / writing config from/to dune.cfg */
	if (!Config_Read("dune.cfg", &g_config)) {
		Config_Default(&g_config);
		commit_dune_cfg = true;
	}
	if (commit_dune_cfg && !Config_Write("dune.cfg", &g_config)) {
		Error("Error writing to dune.cfg file.\n");
		exit(1);
	}

	Input_Init();

	Drivers_All_Init();

	if (!Unknown_25C4_000E()) exit(1);

	g_var_7097 = 0;

	GameLoop_Main();

	printf("%s\n", String_Get_ByIndex(STR_THANK_YOU_FOR_PLAYING_DUNE_II));

	PrepareEnd();
	exit(0);
}
Ejemplo n.º 6
0
static FILE* fopenZIPped(const char* filename, const char* mode)
{
    // check mode
    if (mode[0] == 'r')
    {
        // create the pipe
        int hPipe[2];
        if (_pipe(hPipe, 2048, ((mode[1] =='b') ? _O_BINARY : _O_TEXT) | _O_NOINHERIT) == -1)
        {
            fprintf(stderr, "could not create pipe\n");
            return NULL;
        }

        // duplicate stdin/stdout handle so we can restore them later
        int hStdOut = _dup(_fileno(stdout));

        // make the write end of pipe go to stdout
        if (_dup2(hPipe[WRITE_HANDLE], _fileno(stdout)) != 0)
        {
            fprintf(stderr, "could not set pipe output\n");
            return NULL;
        }

        // redirect read end of pipe to input file
        if (_dup2(hPipe[READ_HANDLE], _fileno(stdin)) != 0)
        {
            fprintf(stderr, "could not redirect input file\n");
            return NULL;
        }

        // close original write end of pipe
        close(hPipe[WRITE_HANDLE]);

        // Spawn process
        HANDLE hProcess = (HANDLE) spawnlp(P_NOWAIT, "unzip", "unzip", "-p", filename, NULL);

        // redirect stdout back into stdout
        if (_dup2(hStdOut, _fileno(stdout)) != 0)
        {
            fprintf(stderr, "could not reconstruct stdout\n");
            return NULL;
        }

        // return redirected stdin
        return stdin;
    }
    else
    {
        return NULL;
    }
}
Ejemplo n.º 7
0
int
daemon(int nochdir, int noclose)
{
	struct sigaction osa, sa;
	int fd;
	pid_t newgrp;
	int oerrno;
	int osa_ok;

	/* A SIGHUP may be thrown when the parent exits below. */
	sigemptyset(&sa.sa_mask);
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = 0;
	osa_ok = __libc_sigaction(SIGHUP, &sa, &osa);

	switch (fork()) {
	case -1:
		return (-1);
	case 0:
		break;
	default:
		/*
		 * A fine point:  _exit(0), not exit(0), to avoid triggering
		 * atexit(3) processing
		 */
		_exit(0);
	}

	newgrp = setsid();
	oerrno = errno;
	if (osa_ok != -1)
		__libc_sigaction(SIGHUP, &osa, NULL);

	if (newgrp == -1) {
		errno = oerrno;
		return (-1);
	}

	if (!nochdir)
		(void)chdir("/");

	if (!noclose && (fd = _open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
		(void)_dup2(fd, STDIN_FILENO);
		(void)_dup2(fd, STDOUT_FILENO);
		(void)_dup2(fd, STDERR_FILENO);
		if (fd > 2)
			(void)_close(fd);
	}
	return (0);
}
Ejemplo n.º 8
0
Archivo: daemon.c Proyecto: marayl/aug
static aug_bool
createconsole_(const char* sname)
{
	int fd;
	FILE* fp;

	HANDLE h;
	CONSOLE_SCREEN_BUFFER_INFO info;

	if (!interactive_(sname) || !AllocConsole())
		return AUG_FALSE;

	fflush(NULL);

	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
	info.dwSize.Y = 512;
	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), info.dwSize);

	h = GetStdHandle(STD_INPUT_HANDLE);
	fd = _open_osfhandle((intptr_t)h, _O_TEXT);
    _dup2(fd, 0);
	fp = _fdopen(fd, "r");
	*stdin = *fp;
	setvbuf(stdin, NULL, _IONBF, 0);

	h = GetStdHandle(STD_OUTPUT_HANDLE);
	fd = _open_osfhandle((intptr_t)h, _O_TEXT);
    _dup2(fd, 1);
	fp = _fdopen(fd, "w");
	*stdout = *fp;
	setvbuf(stdout, NULL, _IONBF, 0);

	h = GetStdHandle(STD_ERROR_HANDLE);
	fd = _open_osfhandle((intptr_t)h, _O_TEXT);
    _dup2(fd, 2);
	fp = _fdopen(fd, "w");
	*stderr = *fp;
	setvbuf(stderr, NULL, _IONBF, 0);

#if defined(_MSC_VER)
	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif /* _MSC_VER */
	return AUG_TRUE;
}
Ejemplo n.º 9
0
int main(int argc, char** argv)
{
	UNUSED(argc);
	UNUSED(argv);

	FileHash_Init();
	Mouse_Init();

	if (A5_InitOptions() == false)
		exit(1);

	char filename[1024];

	snprintf(filename, sizeof(filename), "%s/error.log", g_dune_data_dir);
	FILE* err = fopen(filename, "w");

	snprintf(filename, sizeof(filename), "%s/output.log", g_dune_data_dir);
	FILE* out = fopen(filename, "w");

	_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

	if (err != NULL)
		_dup2(_fileno(err), _fileno(stderr));
	if (out != NULL)
		_dup2(_fileno(out), _fileno(stdout));
	FreeConsole();

	if (!Unknown_25C4_000E())
		exit(1);

	if (A5_Init() == false)
		exit(1);

	Scenario_InitTables();
	Input_Init();
	Audio_LoadSampleSet(SAMPLESET_INVALID);
	String_Init();
	Sprites_Init();
	Sprites_LoadTiles();
	VideoA5_InitSprites();
	GameLoop_TweakWidgetDimensions();
	Audio_PlayVoice(VOICE_STOP);
	GameLoop_GameIntroAnimationMenu();

	printf("%s\n", String_Get_ByIndex(STR_THANK_YOU_FOR_PLAYING_DUNE_II));

	PrepareEnd();
	exit(0);
}
Ejemplo n.º 10
0
OcaOctaveController::OcaOctaveController()
:
  m_state( e_StateStopped ),
  m_lastError( 0 ),
  m_historyFileName( ".octaudio_history" ),
  m_historyBackupFileName( ".octaudio_history_old" ),
  m_host( NULL )
{
  int fds[2] = { -1, -1 };
#ifndef Q_OS_WIN32
  pipe( fds );
  dup2( fds[1], fileno(stdout) );
  setvbuf( stdout, NULL, _IOLBF, 0 );
  close( fds[1] );
  m_pipeFd = fds[0];
  int result = fcntl( m_pipeFd,  F_SETFL, O_NONBLOCK );
  Q_ASSERT( 0 == result );
  (void) result;
  QSocketNotifier* pNotifier = new QSocketNotifier( m_pipeFd,
                                                    QSocketNotifier::Read, this );
  connect( pNotifier, SIGNAL(activated(int)), SLOT(readStdout()) );
#else
  _pipe( fds, 4096, O_BINARY );
  _dup2( fds[1], fileno(stdout) );
  setvbuf( stdout, NULL, _IOLBF, 0 );
  close( fds[1] );
  m_pipeFd = fds[0];

  m_stdoutThread = new OcaStdoutThread( this );
  m_stdoutThread->start();
#endif
}
Ejemplo n.º 11
0
R_API int r_cons_pipe_open(const char *file, int append) {
	int fd = open (file, O_BINARY | O_RDWR | O_CREAT | (append?O_APPEND:O_TRUNC), 0644);
	if (fd==-1) {
		eprintf ("Cannot open file '%s'\n", file);
		return -1;
	}// else eprintf ("%s created\n", file);

	if (backup_fd != -1)
		close (backup_fd);
#if __WINDOWS__
	backup_fd = 2002-(fd-2); // windows xp has 2048 as limit fd
	if (_dup2 (1, backup_fd) == -1) {
#else
	backup_fd = sysconf (_SC_OPEN_MAX)-(fd-2); // portable getdtablesize()
	if (dup2 (1, backup_fd) == -1) {
#endif
		eprintf ("Cannot dup stdout to %d\n", backup_fd);
		return -1;
	}
	close (1);
	dup2 (fd, 1);
	return fd;
}

R_API void r_cons_pipe_close(int fd) {
	if (fd == -1)
		return;
	close (fd);
	if (backup_fd != -1) {
		dup2 (backup_fd, 1);
		close (backup_fd);
		backup_fd = -1;
	}
}
Ejemplo n.º 12
0
CGlobal::CGlobal()
{
    debugger_.reset(new Debugger());

    // redirect 'stdout' to the pipe

    char path[MAX_PATH];
    ::GetTempPath(MAX_PATH, path);
    char temp[MAX_PATH];
    ::GetTempFileName(path, "lu-", ::GetTickCount(), temp);

    // open stdout first, or else dup2 won't work
    if (freopen(temp, "w", stdout) == 0)
        throw std::exception("error redirecting stdout to temp file");

    if (_pipe(stdout_fds_, 0, _O_BINARY) != 0 || _dup2(stdout_fds_[1], _fileno(stdout)) != 0)
        throw std::exception("error redirecting stdout to the pipe");

    // no buffering for stdout, to make output window refresh instant
    setvbuf(stdout, NULL, _IONBF, 0);

    //TODO: delete temp
    ::DeleteFile(temp);

    output_position_ = 0;
    output_.reserve(200);

    thread_ = ::AfxBeginThread(ReadStdoutText, this, 0, 0, CREATE_SUSPENDED);
    if (thread_ == 0)
        throw std::exception("cannot create worker thread");
    thread_->m_bAutoDelete = false;
    thread_->ResumeThread();
}
Ejemplo n.º 13
0
int
duplicate(int fd, int newfd, Bool useDup2) {
  if (useDup2) {
    return _dup2(fd, newfd);
  }

  return _dup(fd);
}
Ejemplo n.º 14
0
void DynamicResponseState::execveCgiProgram(){
	char *emptylist[]={NULL};
	if(_fork()==0){
		setenv("QUERY_STRING",cgiArgs.c_str(),1);
		_dup2(getFileDescriptor(),STDOUT_FILENO);
		_execve(getFileName().c_str(),emptylist,environ);
	}
	_wait(NULL);
}
Ejemplo n.º 15
0
DevNull::~DevNull()
{
    _close(null_);
    if (orig_ != INVALID_FD)
    {
        _dup2(clone_, orig_);
        _close(clone_);
    }
}
Ejemplo n.º 16
0
static int do_dump_do(sc_card_t *card, unsigned int tag)
{
	int r;
	size_t length;
	unsigned char buffer[254];	// Private DO are specified up to 254 bytes

	memset(buffer, '\0', sizeof(buffer));

	if (tag < 0x101 || tag > 0x104) {
		util_error("illegal DO identifier %04X", tag);
		return SC_ERROR_INVALID_ARGUMENTS;
	}

	r = sc_get_data(card, tag, buffer, sizeof(buffer));
	if (r < 0) {
		util_error("failed to get data object DO %04X: %s", tag, sc_strerror(r));
		if (SC_ERROR_SECURITY_STATUS_NOT_SATISFIED == r) {
			util_error("make sure the 'verify' and 'pin' parameters are correct");
		}
		return r;
	}
	length = (size_t) r;	/* r is guaranteed to be non-negative */

	if (opt_raw) {
		int tmp;
		FILE *fp;

#ifndef _WIN32
		tmp = dup(fileno(stdout));
#else
		tmp = _dup(_fileno(stdout));
#endif
		if (tmp < 0)
			return EXIT_FAILURE;
		fp = freopen(NULL, "wb", stdout);
		if (fp) {
			r = (int) fwrite(buffer, sizeof(char), length, fp);
		}
#ifndef _WIN32
		dup2(tmp, fileno(stdout));
#else
		_dup2(tmp, _fileno(stdout));
#endif
		clearerr(stdout);
		close(tmp);

		if (length != (size_t) r)	/* fail on write errors */
			return EXIT_FAILURE;
	} else {
		util_hex_dump_asc(stdout, buffer, length, -1);
	}

	return EXIT_SUCCESS;
}
Ejemplo n.º 17
0
pid_t
background_and_capture(char cmd[], int user_sh, FILE **out, FILE **err)
{
	int out_fd, out_pipe[2];
	int err_fd, err_pipe[2];
	pid_t pid;

	if(_pipe(out_pipe, 512, O_NOINHERIT) != 0)
	{
		show_error_msg("File pipe error", "Error creating pipe");
		return (pid_t)-1;
	}

	if(_pipe(err_pipe, 512, O_NOINHERIT) != 0)
	{
		show_error_msg("File pipe error", "Error creating pipe");
		close(out_pipe[0]);
		close(out_pipe[1]);
		return (pid_t)-1;
	}

	out_fd = dup(_fileno(stdout));
	err_fd = dup(_fileno(stderr));

	pid = background_and_capture_internal(cmd, user_sh, out, err, out_pipe,
			err_pipe);

	_close(out_pipe[1]);
	_close(err_pipe[1]);

	_dup2(out_fd, _fileno(stdout));
	_dup2(err_fd, _fileno(stderr));

	if(pid == (pid_t)-1)
	{
		_close(out_pipe[0]);
		_close(err_pipe[0]);
	}

	return pid;
}
Ejemplo n.º 18
0
void
ns_os_daemonize(void) {
	/*
	 * Try to set stdin, stdout, and stderr to /dev/null, but press
	 * on even if it fails.
	 */
	if (devnullfd != -1) {
		if (devnullfd != _fileno(stdin)) {
			close(_fileno(stdin));
			(void)_dup2(devnullfd, _fileno(stdin));
		}
		if (devnullfd != _fileno(stdout)) {
			close(_fileno(stdout));
			(void)_dup2(devnullfd, _fileno(stdout));
		}
		if (devnullfd != _fileno(stderr)) {
			close(_fileno(stderr));
			(void)_dup2(devnullfd, _fileno(stderr));
		}
	}
}
Ejemplo n.º 19
0
OutputLogger::~OutputLogger(void)
{
	// Replace fd with it's original details
	if (fileOld && fd >= 0) {
		_dup2(_fileno(fileOld),fd);
		fd = -1;
	}

	if (pThread) {
		// Wait for the thread to exit (the write handle is now invalid so it will have broken the pipe)
		SDL_WaitThread(pThread,NULL);
		pThread = NULL;
	}

	// Close the read end of the pipe, completely closing the pipe
	if (fdPipeRead >= 0) {
		_close(fdPipeRead);
		fdPipeRead = -1;
	}

	// Close the duplicated original file
	if (fileOld) {
		std::fclose(fileOld);
		fileOld = NULL;
	}

	// Close the log file
	if (fileLog) {

		// In the event that we did a freopen on the handle remove the windows
		// output std handle
#ifdef WIN32
		DWORD stdhandle = 0;
		if (fileLog == stdout) 
			stdhandle = STD_OUTPUT_HANDLE;
		else if (fileLog == stderr) 
			stdhandle = STD_ERROR_HANDLE;
		if (stdhandle) 
			SetStdHandle(stdhandle,NULL);
#endif

		// Get the size written to the log file
		int sizeLog = std::ftell(fileLog);

		std::fclose(fileLog);
		fileLog = NULL;

		// Delete the log file if it was empty
		if (!sizeLog) std::remove(filenameLog.c_str());
		filenameLog = std::string();
	}

}
Ejemplo n.º 20
0
//!
//! Nullify given open file descriptor.
//!
DevNull::DevNull(int fd)
{
    orig_ = fd;
    clone_ = _dup(orig_);

#pragma warning(push)
#pragma warning(disable: 4996)
    null_ = _wopen(DEV_NULL, _O_RDWR);
#pragma warning(pop)

    _dup2(null_, orig_);
}
Ejemplo n.º 21
0
	ShellWrapper()
	{
		int iReturn;
		iReturn = _pipe(iPipeIn_, 512, _O_TEXT | O_NOINHERIT);
		assert(iReturn != -1);
		iReturn = _pipe(iPipeOut_, 512, _O_TEXT | O_NOINHERIT);
		assert(iReturn != -1);

		//save old handle
		int iStdin = _dup(_fileno(stdin));
		int iStdout = _dup(_fileno(stdout));
		int iStderr = _dup(_fileno(stderr));

		iReturn = _dup2(iPipeOut_[0], _fileno(stdin));
		assert(iReturn == 0);
		iReturn = _dup2(iPipeIn_[1], _fileno(stdout));
		assert(iReturn == 0);
		iReturn = _dup2(iPipeIn_[1], _fileno(stderr));
		assert(iReturn == 0);

		char *arg[] = {"cmd.exe", "/Q", "/A", NULL};
		iSubProcess_ = spawnvp(P_NOWAIT, arg[0], arg);

		//restore old handle
		iReturn = _dup2(iStdin, _fileno(stdin));
		iReturn = _dup2(iStdout, _fileno(stdout));
		iReturn = _dup2(iStderr, _fileno(stderr));
	}
Ejemplo n.º 22
0
R_API int r_cons_pipe_open(const char *file, int fdn, int append) {
	char *targetFile;
	if (fdn < 1) {
		return -1;
	}
	if (!strncmp (file, "~/", 2) || !strncmp (file, "~\\", 2)) {
		targetFile = r_str_home (file + 2);
	} else {
		targetFile = strdup (file);
	}
	int fd = r_sandbox_open (targetFile,
		O_BINARY | O_RDWR | O_CREAT | (append? O_APPEND: O_TRUNC), 0644);
	if (fd==-1) {
		eprintf ("r_cons_pipe_open: Cannot open file '%s'\n", file);
		free (targetFile);
		return -1;
	}// else eprintf ("%s created\n", file);
	if (backup_fd != -1) {
		close (backup_fd);
	}
	backup_fdn = fdn;
#if __WINDOWS__ && !__CYGWIN__
	backup_fd = 2002-(fd-2); // windows xp has 2048 as limit fd
	if (_dup2 (fdn, backup_fd) == -1) {
#else
	backup_fd = sysconf (_SC_OPEN_MAX)-(fd-2); // portable getdtablesize()
	if (backup_fd < 2) {
		backup_fd = 2002 - (fd - 2); // fallback
	}
	if (dup2 (fdn, backup_fd) == -1) {
#endif
		eprintf ("Cannot dup stdout to %d\n", backup_fd);
		free (targetFile);
		return -1;
	}
	close (fdn);
	dup2 (fd, fdn);
	free (targetFile);
	return fd;
}

R_API void r_cons_pipe_close(int fd) {
	if (fd == -1) {
		return;
	}
	close (fd);
	if (backup_fd != -1) {
		dup2 (backup_fd, backup_fdn);
		close (backup_fd);
		backup_fd = -1;
	}
}
Ejemplo n.º 23
0
void Log::SetMode(int mode) {
    
    if (mode & ToDebug)
        m_todebug = true;
    else
        m_todebug = false;

    if (mode & ToFile)  {
        m_tofile = true;
    } else {
        CloseFile();
        m_tofile = false;
    }
    
#ifdef _WIN32_WCE
	m_toconsole = false;
#else
    if (mode & ToConsole) {
        if (!m_toconsole) {
            AllocConsole();
            fclose(stdout);
            fclose(stderr);
#ifdef _MSC_VER
            int fh = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0);
            _dup2(fh, 1);
            _dup2(fh, 2);
            _fdopen(1, "wt");
            _fdopen(2, "wt");
            printf("fh is %d\n",fh);
            fflush(stdout);
#endif
        }

        m_toconsole = true;
    } else {
        m_toconsole = false;
    }
#endif
}
Ejemplo n.º 24
0
OutputLogger::OutputLogger(FILE *file, const std::string &filename) :
	fd(-1), fileOld(NULL), filenameLog(filename), fileLog(NULL), 	
	fdPipeRead(-1), pThread(NULL)
{
	// Get the underlying file descriptor for the FILE stream
	fd = _fileno(file);

	// Probably on windows and there is no stdout/stderr in Subsystem Windows
	if (fd < 0) {
		fileLog = freopen(filenameLog.c_str(),"w",file);
#ifdef WIN32
		DWORD stdhandle = 0;
		if (fileLog == stdout) 
			stdhandle = STD_OUTPUT_HANDLE;
		else if (fileLog == stderr) 
			stdhandle = STD_ERROR_HANDLE;
		if (stdhandle) 
			SetStdHandle(stdhandle,(HANDLE)_get_osfhandle(_fileno(fileLog)));
#endif
		return;
	}

	// Create the pipe
	int fdsPipe[2];
	if (_pipe(fdsPipe,256,_O_BINARY) != 0) {
		return;
	}
	fdPipeRead = fdsPipe[0];
	int fdPipeWrite = fdsPipe[1];

	// Make sure that buffering is turned off on the incoming file
	std::setvbuf(file,NULL,_IONBF,0);

	// Duplicate the fd and create new filestream for it
	fileOld = _fdopen(_dup(fd),"w");
	// If the file was stderr, make sure the new file doesn't have buffering
	if (fileOld && file == stderr) std::setvbuf(fileOld,NULL,_IONBF,0);

	// Create the output log file
	fileLog =  std::fopen(filenameLog.c_str(),"w");

	// Duplicate pipe write file descriptor and replace original
	_dup2(fdPipeWrite,fd);
	
	// Close the fd for the write end of the pipe
	_close(fdPipeWrite);
	fdPipeWrite = -1;

	// Create the thread
	pThread = SDL_CreateThread( (int (SDLCALL*)(void*)) &OutputLogger::sThreadMain,this);
}
Ejemplo n.º 25
0
static void
IoRedirect(signal_user_data_t *ud)
{
    GIOChannel *channel;
    gint pfd[2];
    gchar *config, *path, *str;
    pid_t pid;

    // I'm opening a pipe and attaching the writer end to stderr
    // The reader end will be polled by main event loop and I'll get
    // a callback when there is data available.
    if (pipe( pfd ) < 0)
    {
        g_warning("Failed to redirect IO. Logging impaired\n");
        return;
    }
    clean_old_logs();
    // Open activity log.
    config = ghb_get_user_config_dir(NULL);
    pid = getpid();
    path = g_strdup_printf("%s/Activity.log.%d", config, pid);
    ud->activity_log = g_io_channel_new_file (path, "w", NULL);
    ud->job_activity_log = NULL;
    str = g_strdup_printf("<big><b>%s</b></big>", path);
    ghb_ui_update(ud, "activity_location", ghb_string_value(str));
    g_free(str);
    g_free(path);
    g_free(config);
    // Set encoding to raw.
    g_io_channel_set_encoding(ud->activity_log, NULL, NULL);
    // redirect stderr to the writer end of the pipe

#if defined(_WIN32)
    _dup2(pfd[1], _fileno(stderr));
#else
    dup2(pfd[1], STDERR_FILENO);
#endif
    setvbuf(stderr, NULL, _IONBF, 0);

#if defined(_WIN32)
    channel = g_io_channel_win32_new_fd(pfd[0]);
#else
    channel = g_io_channel_unix_new(pfd[0]);
#endif

    // I was getting an this error:
    // "Invalid byte sequence in conversion input"
    // Set disable encoding on the channel.
    g_io_channel_set_encoding(channel, NULL, NULL);
    g_io_add_watch(channel, G_IO_IN, ghb_log_cb, (gpointer)ud );
}
Ejemplo n.º 26
0
int main( int argc, char** argv ) {
 if ( argc < 2 ) puts( "err2out is stdERR TO stdOUT redirector, version 2.2\nCopyright (c) 2002-2003 Denis Ryzhkov ( Creon )\nhttp://creon.cjb.net/?soft/err2out\n\nExamples:\nerr2out \"C:\\Program Files\\jdk\\bin\\javac\" Some.java | more\nerr2out \"C:\\Program Files\\jdk\\bin\\javac\" Some.java > err.txt\nerr2out \"C:\\Program Files\\jdk\\bin\\javac\" Some.java >> err.txt" );
 else {
  _dup2( 1, 2 ); // redirect 2=stderr to 1=stdout
  char** argz = new char*[ argc ]; // -argv[ 0 ], +end0
  argz[ argc - 1 ] = 0; // end0
  for ( int i = 0; i < argc - 1; i++ )
   sprintf( argz[ i ] = new char[ strlen( argv[ i + 1 ] ) + 3 ], // \" \" \000
     "\"%s\"", argv[ i + 1 ] );
  _spawnv( _P_WAIT, argv[ 1 ], argz );
  for ( i = 0; i < argc - 1; i++ ) delete[] argz[ i ];
  delete[] argz;
 }
 return 0;
}
Ejemplo n.º 27
0
INT32 ossDup2( int oldFd, int newFd )
{
#if defined( _WINDOWS )
   if ( _dup2( oldFd, newFd ) != 0 )
   {
      return SDB_SYS ;
   }
#else
   if ( dup2( oldFd, newFd ) < 0 )
   {
      return SDB_SYS ;
   }
#endif // _WINDOWS
   return SDB_OK ;
}
Ejemplo n.º 28
0
/**
 * @brief
 *	manipulates the file descriptor fd.
 *
 * @param[in] fd - file descriptor
 * @param[in] cmd - operation to be performed
 * @param[in] arg - new fd
 *
 * @return	int
 * @retval	0	success
 * @retval	-2	error
 *
 */
int
fcntl(int fd, int cmd, long arg)
{

	if (cmd == F_DUPFD) {
		/* dup2 is deprecated POSIX function. Hence using the ISO C++ conformant
		 * _dup2 instead. _dup2 functions associate a second file descriptor with
		 * a currently open file and returns 0 to indicate success.
		 */

		if (_dup2(fd, arg)== 0)
			return (arg);
	}
	return (-2);
}
Ejemplo n.º 29
0
static int do_dump_do(sc_card_t *card, unsigned int tag)
{
	int r, tmp;
	FILE *fp;

	// Private DO are specified up to 254 bytes
	unsigned char buffer[254];
	memset(buffer, '\0', sizeof(buffer));

	r = sc_get_data(card, tag, buffer, sizeof(buffer));
	if (r < 0) {
		printf("Failed to get data object: %s\n", sc_strerror(r));
		if(SC_ERROR_SECURITY_STATUS_NOT_SATISFIED == r) {
			printf("Make sure the 'verify' and 'pin' parameters are correct.\n");
		}
		return r;
	}

	if(opt_raw) {
		r = 0;
		#ifndef _WIN32
		tmp = dup(fileno(stdout));
		#else
		tmp = _dup(_fileno(stdout));
		#endif
		if (tmp < 0)
			return EXIT_FAILURE;
		fp = freopen(NULL, "wb", stdout);
		if (fp) {
			r = (int)fwrite(buffer, sizeof(char), sizeof(buffer), fp);
		}
		#ifndef _WIN32
		dup2(tmp, fileno(stdout));
		#else
		_dup2(tmp, _fileno(stdout));
		#endif
		clearerr(stdout);
		close(tmp);
		if (sizeof(buffer) != r)
			return EXIT_FAILURE;
	} else {
		util_hex_dump_asc(stdout, buffer, sizeof(buffer), -1);
	}

	return EXIT_SUCCESS;
}
Ejemplo n.º 30
0
static FILE *my_win_freopen(const char *path, const char *mode, FILE *stream)
{
  int handle_fd, fd= _fileno(stream);
  HANDLE osfh;

  DBUG_ASSERT(path && stream);

  /* Services don't have stdout/stderr on Windows, so _fileno returns -1. */
  if (fd < 0)
  {
    if (!freopen(path, mode, stream))
      return NULL;

    fd= _fileno(stream);
  }

  if ((osfh= CreateFile(path, GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE |
                        FILE_SHARE_DELETE, NULL,
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL,
                        NULL)) == INVALID_HANDLE_VALUE)
  {
    _close(fd);
    return NULL;
  }

  if ((handle_fd= _open_osfhandle((intptr_t)osfh,
                                  _O_APPEND | _O_TEXT)) == -1)
  {
    CloseHandle(osfh);
    return NULL;
  }

  if (_dup2(handle_fd, fd) < 0)
  {
    CloseHandle(osfh);
    return NULL;
  }

  _close(handle_fd);

  return stream;
}