void RedirectIoToConsole() { int hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE* fp = NULL; // allocate a console for this app AllocConsole(); // http://softwareforums.intel.com/ids/board/message?board.id=15&message.id=2971&page=1&view=by_threading // would like to see messages without mousing around each time I run { char name[256]; HWND win; GetConsoleTitle( name, 255 ); win = FindWindow( NULL, name ); SetWindowPos( win, HWND_TOP, 0, 640, 640, 480, SWP_NOSIZE ); ShowWindow( win, SW_SHOWNORMAL ); } // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r" ); *stdin = *fp; setvbuf( stdin, NULL, _IONBF, 0 ); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stderr = *fp; setvbuf( stderr, NULL, _IONBF, 0 ); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well // ios::sync_with_stdio(); }
/*! * \brief Connect to a radio station. * * \param sock TCP socket for this connection. * \param ip IP address of the server to connect. * \param port Port number of the server to connect. * * \return Stream pointer of the established connection on success. * Otherwise 0 is returned. */ FILE *ConnectStation(TCPSOCKET *sock, u_long ip, u_short port, u_long *metaint, RADIO_STREAM rStream) { int rc; FILE *stream; u_char *line; u_char *cp; /* * Connect the TCP server. */ // printf("radio ip: %d", rStream.ip) printf("Connecting %s:%d...", rStream.radio_ip, rStream.radio_port); if ((rc = NutTcpConnect(sock, inet_addr(rStream.radio_ip), rStream.radio_port))) { printf("Error: Connect failed with %d\n", NutTcpError(sock)); return 0; } puts("OK"); if ((stream = _fdopen((int) sock, "r+b")) == 0) { puts("Error: Can't create stream"); return 0; } /* * Send the HTTP request. */ printf("GET %s HTTP/1.0\n\n", rStream.radio_url); fprintf(stream, "GET %s HTTP/1.0\r\n", rStream.radio_url); fprintf(stream, "Host: %s\r\n", rStream.radio_ip); fprintf(stream, "User-Agent: Ethernut\r\n"); fprintf(stream, "Accept: */*\r\n"); fprintf(stream, "Icy-MetaData: 1\r\n"); fprintf(stream, "Connection: close\r\n"); fputs("\r\n", stream); fflush(stream); /* * Receive the HTTP header. */ line = malloc(MAX_HEADERLINE); while (fgets(line, MAX_HEADERLINE, stream)) { /* * Chop off the carriage return at the end of the line. If none * was found, then this line was probably too large for our buffer. */ cp = strchr(line, '\r'); if (cp == 0) { puts("Warning: Input buffer overflow"); continue; } *cp = 0; /* * The header is terminated by an empty line. */ if (*line == 0) { break; } if (strncmp(line, "icy-metaint:", 12) == 0) { *metaint = atol(line + 12); } printf("%s\n", line); } putchar('\n'); free(line); return stream; }
BOOL CStdioFile::Open(LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pException) { ASSERT(pException == NULL || AfxIsValidAddress(pException, sizeof(CFileException))); ASSERT(lpszFileName != NULL); ASSERT(AfxIsValidString(lpszFileName)); m_pStream = NULL; if (!CFile::Open(lpszFileName, (nOpenFlags & ~typeText), pException)) return FALSE; ASSERT(m_hFile != hFileNull); ASSERT(m_bCloseOnDelete); char szMode[4]; // C-runtime open string int nMode = 0; // determine read/write mode depending on CFile mode if (nOpenFlags & modeCreate) { if (nOpenFlags & modeNoTruncate) szMode[nMode++] = 'a'; else szMode[nMode++] = 'w'; } else if (nOpenFlags & modeWrite) szMode[nMode++] = 'a'; else szMode[nMode++] = 'r'; // add '+' if necessary (when read/write modes mismatched) if (szMode[0] == 'r' && (nOpenFlags & modeReadWrite) || szMode[0] != 'r' && !(nOpenFlags & modeWrite)) { // current szMode mismatched, need to add '+' to fix szMode[nMode++] = '+'; } // will be inverted if not necessary int nFlags = _O_RDONLY|_O_TEXT; if (nOpenFlags & (modeWrite|modeReadWrite)) nFlags ^= _O_RDONLY; if (nOpenFlags & typeBinary) szMode[nMode++] = 'b', nFlags ^= _O_TEXT; else szMode[nMode++] = 't'; szMode[nMode++] = '\0'; // open a C-runtime low-level file handle int nHandle = _open_osfhandle(m_hFile, nFlags); // open a C-runtime stream from that handle if (nHandle != -1) m_pStream = _fdopen(nHandle, szMode); if (m_pStream == NULL) { // an error somewhere along the way... if (pException != NULL) { pException->m_lOsError = _doserrno; pException->m_cause = CFileException::OsErrorToException(_doserrno); } CFile::Abort(); // close m_hFile return FALSE; } return TRUE; }
// extra pointer is used to hold process id to wait on to close // NB: stdin is opened as "wb", stdout, stderr as "r" int my_popen3 (pipeinfo_t *p) { FILE *fin = NULL; FILE *fout = NULL; FILE *ferr = NULL; HANDLE child_hin = INVALID_HANDLE_VALUE; HANDLE child_hout = INVALID_HANDLE_VALUE; HANDLE child_herr = INVALID_HANDLE_VALUE; HANDLE parent_hin = INVALID_HANDLE_VALUE; HANDLE parent_hout = INVALID_HANDLE_VALUE; HANDLE parent_herr = INVALID_HANDLE_VALUE; puser_t *puser = NULL; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; SECURITY_ATTRIBUTES sa; puser = malloc (sizeof (puser_t)); if (!puser) return 0; puser->proc = INVALID_HANDLE_VALUE; puser->thread = INVALID_HANDLE_VALUE; // make the pipes sa.nLength = sizeof (sa); sa.bInheritHandle = 1; sa.lpSecurityDescriptor = NULL; if (!CreatePipe (&child_hin, &parent_hin, &sa, 0)) goto fail; if (!CreatePipe (&parent_hout, &child_hout, &sa, 0)) goto fail; if (!CreatePipe (&parent_herr, &child_herr, &sa, 0)) goto fail; // very important if (!SetHandleInformation (parent_hin, HANDLE_FLAG_INHERIT, 0)) goto fail; if (!SetHandleInformation (parent_hout, HANDLE_FLAG_INHERIT, 0)) goto fail; if (!SetHandleInformation (parent_herr, HANDLE_FLAG_INHERIT, 0)) goto fail; // start the child process ZeroMemory (&siStartInfo, sizeof (STARTUPINFO)); siStartInfo.cb = sizeof (STARTUPINFO); siStartInfo.hStdInput = child_hin; siStartInfo.hStdOutput = child_hout; siStartInfo.hStdError = child_herr; siStartInfo.dwFlags = STARTF_USESTDHANDLES; if (!CreateProcess(NULL,// application name (LPTSTR)p->command,// command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited DETACHED_PROCESS, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo)) // receives PROCESS_INFORMATION { goto fail; } puser->proc = piProcInfo.hProcess; puser->thread = piProcInfo.hThread; // what the hell is this cast for if (NULL == (fin = _fdopen (_open_osfhandle ((int) parent_hin, 0), "wb"))) goto fail; if (NULL == (fout = _fdopen (_open_osfhandle ((int) parent_hout, 0), "r"))) goto fail; if (NULL == (ferr = _fdopen (_open_osfhandle ((int) parent_herr, 0), "r"))) goto fail; // after fdopen(osf()), we don't need to keep track of parent handles anymore // fclose on the FILE struct will automatically free them p->user = puser; p->f_stdin = fin; p->f_stdout = fout; p->f_stderr = ferr; CloseHandle (child_hin); CloseHandle (child_hout); CloseHandle (child_herr); return 1; fail: if (fin) fclose (fin); if (fout) fclose (fout); if (ferr) fclose (ferr); if (puser->proc) CloseHandle (puser->proc); if (puser->thread) CloseHandle (puser->thread); if (child_hin != INVALID_HANDLE_VALUE) CloseHandle (child_hin); if (child_hout != INVALID_HANDLE_VALUE) CloseHandle (child_hout); if (child_herr != INVALID_HANDLE_VALUE) CloseHandle (child_herr); if (parent_hin != INVALID_HANDLE_VALUE) CloseHandle (parent_hin); if (parent_hout != INVALID_HANDLE_VALUE) CloseHandle (parent_hout); if (parent_herr != INVALID_HANDLE_VALUE) CloseHandle (parent_herr); free (puser); return 0; }
/* Runs command in a background and redirects its stdout and stderr streams to * file streams which are set. Returns (pid_t)0 or (pid_t)-1 on error. */ static pid_t background_and_capture_internal(char cmd[], int user_sh, FILE **out, FILE **err, int out_pipe[2], int err_pipe[2]) { wchar_t *args[4]; char cwd[PATH_MAX]; int code; wchar_t *final_wide_cmd; wchar_t *wide_sh = NULL; if(_dup2(out_pipe[1], _fileno(stdout)) != 0) return (pid_t)-1; if(_dup2(err_pipe[1], _fileno(stderr)) != 0) return (pid_t)-1; cwd[0] = '\0'; if(get_cwd(cwd, sizeof(cwd)) != NULL) { if(is_unc_path(cwd)) { (void)chdir(get_tmpdir()); } } final_wide_cmd = to_wide(cmd); wide_sh = to_wide(user_sh ? cfg.shell : "cmd"); if(!user_sh || curr_stats.shell_type == ST_CMD) { args[0] = wide_sh; args[1] = L"/C"; args[2] = final_wide_cmd; args[3] = NULL; } else { args[0] = wide_sh; args[1] = L"-c"; args[2] = final_wide_cmd; args[3] = NULL; } code = _wspawnvp(P_NOWAIT, args[0], (const wchar_t **)args); free(wide_sh); free(final_wide_cmd); if(is_unc_path(cwd)) { (void)chdir(cwd); } if(code == 0) { return (pid_t)-1; } if((*out = _fdopen(out_pipe[0], "r")) == NULL) return (pid_t)-1; if((*err = _fdopen(err_pipe[0], "r")) == NULL) { fclose(*out); return (pid_t)-1; } return 0; }
int main() #endif { { int hCrt; FILE *hf; AllocConsole(); //::AttachConsole(ATTACH_PARENT_PROCESS); hCrt = _open_osfhandle( (long) GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT ); hf = _fdopen( hCrt, "w" ); *stdout = *hf; /*i = */setvbuf( stdout, NULL, _IONBF, 0 ); } const wchar_t *pipeName = BREAKPAD_PIPE_NAME; const ::LPSECURITY_ATTRIBUTES securityAttributes = NULL; void* connect_context = 0; void* dump_context = 0; void* exit_context = 0; const bool generate_dumps = true; const std::wstring dump_path = L"c:\\temp"; std::cout << "---------------------------------------------------------------------------------------" << std::endl; std::cout << "Creating CrashGenerationServer" << std::endl; void* upload_context = 0; google_breakpad::CrashGenerationServer server(pipeName, securityAttributes, onClientConnectedCallback, connect_context, onClientDumpRequestCallback, dump_context, onClientExitedCallback, exit_context, onClientUploadRequestCallback, upload_context, generate_dumps, &dump_path); std::cout << "Starting CrashGenerationServer..." << std::endl; if (!server.Start()) { std::cerr << "failed to start" << std::endl; return -1; } std::cout << "\tsuccess!" << std::endl; #ifdef WINDOWS_APP ::MSG msg; for (;;) { std::cout << "alive... " << std::endl; ::BOOL messageAvailable = ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); if (messageAvailable == 0) { Sleep(1000); continue; } ::BOOL success = GetMessage(&msg, NULL, 0, 0); if (0 != success) { std::cerr << "Unable to get next Windows message. Exiting" << std::endl; break; } if (-1 == success) { std::cerr << "Windowing message pump error" << std::endl; return -1; } else { std::cout << "WM message " << msg.message << std::endl; TranslateMessage(&msg); DispatchMessage(&msg); } } const int exitCode = (int)msg.wParam; std::cout << "Exiting..." << exitCode << std::endl; return exitCode; #else for (;;) { std::cout << "alive... " << std::endl; ::Sleep(1000); } #endif }
FILE *openpipe(char *command, unsigned short redirect_stderr) { SECURITY_ATTRIBUTES sa = {0}; STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; BOOL bTest= 0; DWORD dwNumberOfBytesRead = 0; FILE *stream; int CrtFileHandle; hPipeOutputRead = hPipeOutputWrite = hPipeInputRead = hPipeInputWrite = NULL; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if(!CreatePipe(&hPipeOutputRead,&hPipeOutputWrite,&sa,0)) { mexPrintf("Can't open stdout pipe\n"); return(NULL); } if(!CreatePipe(&hPipeInputRead,&hPipeInputWrite,&sa,0)) { mexPrintf("Can't open stdin pipe\n"); return(NULL); } si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.wShowWindow = SW_HIDE; si.hStdInput = hPipeInputRead; si.hStdOutput = hPipeOutputWrite; if(redirect_stderr) si.hStdError = hPipeOutputWrite; if(CreateProcess(NULL, command, NULL, NULL, TRUE, HIGH_PRIORITY_CLASS, NULL, NULL, &si, &pi) == 0) { mexPrintf("Could not execute subprocess\n"); return(NULL); } CloseHandle(hPipeOutputWrite); CloseHandle(hPipeInputRead); /* Convert OS file handle to CRT file pointer */ if((CrtFileHandle = _open_osfhandle((long)hPipeOutputRead, _O_RDONLY|_O_BINARY)) == -1) { mexPrintf("Could not translate windows handle to crt handle\n"); return(NULL); } /* Change handle access to stream access. */ if((stream = _fdopen(CrtFileHandle, "r+b")) == NULL) { mexPrintf("Could not open FILE * for pipe\n"); return(NULL); } subprocess = pi.hProcess; return(stream); }
rt_public void eif_show_console(void) /* Create a new DOS console if needed (i.e. in case of a Windows application. */ { if (!eif_console_allocated) { HANDLE eif_conin, eif_conout, eif_conerr; CONSOLE_SCREEN_BUFFER_INFO csbi; BOOL bLaunched; int hCrt; STARTUPINFO l_info; #ifndef EIF_BORLAND FILE *hf; #endif RT_GET_CONTEXT /* Find out if the calling process has initialized the HANDLEs. */ memset(&l_info, 0, sizeof(STARTUPINFO)); GetStartupInfo(&l_info); if ((l_info.dwFlags & STARTF_USESTDHANDLES) != STARTF_USESTDHANDLES) { AllocConsole(); } /* Get all default standard handles */ eif_conin = GetStdHandle (STD_INPUT_HANDLE); eif_conout = GetStdHandle (STD_OUTPUT_HANDLE); eif_conerr = GetStdHandle (STD_ERROR_HANDLE); /* Check if handles are available, allocate console if not */ /* Raise an I/O exception if we cannot get a valid handle */ if ((eif_conin == 0) || (eif_conin == INVALID_HANDLE_VALUE)) { AllocConsole (); eif_conin = GetStdHandle (STD_INPUT_HANDLE); } if (eif_conin == INVALID_HANDLE_VALUE) { eio (); } if ((eif_conout == 0) || (eif_conout == INVALID_HANDLE_VALUE)){ AllocConsole (); eif_conout = GetStdHandle (STD_OUTPUT_HANDLE); } if (eif_conout == INVALID_HANDLE_VALUE) { eio (); } if ((eif_conerr == 0) || (eif_conerr == INVALID_HANDLE_VALUE)) { AllocConsole (); eif_conerr = GetStdHandle (STD_ERROR_HANDLE); } if (eif_conerr == INVALID_HANDLE_VALUE) { eio (); } /* If console was manually created, we are most likely in * a Windows application that tries to output something. * Therefore we need to correctly associated all standard * handles `stdin', `stdout' and `stderr' to the new * created console. * Code was adapted from http://codeguru.earthweb.com/console/Console.html * But also checkout Microsoft support web site: * http://support.microsoft.com/default.aspx?scid=kb;EN-US;q105305 * * Note: For Borland, the above trick does not work, one has to * duplicate the handle, unfortunately the solution does not work * with Microsoft which explains the ifdef statement. */ EIF_CONSOLE_LOCK; if (!eif_console_allocated) { if (_get_osfhandle (_fileno (stdout)) != (intptr_t) eif_conout) { hCrt = _open_osfhandle ((intptr_t) eif_conout, _O_TEXT); #ifdef EIF_BORLAND dup2 (hCrt, _fileno(stdout)); #else hf = _fdopen (hCrt, "w"); *stdout = *hf; #endif setvbuf(stdout, NULL, _IONBF, 0); } if (_get_osfhandle (_fileno (stderr)) != (intptr_t) eif_conerr) { hCrt = _open_osfhandle ((intptr_t) eif_conerr, _O_TEXT); #ifdef EIF_BORLAND dup2 (hCrt, _fileno(stderr)); #else hf = _fdopen (hCrt, "w"); *stderr = *hf; #endif setvbuf(stderr, NULL, _IONBF, 0); } if (_get_osfhandle (_fileno (stdin)) != (intptr_t) eif_conin) { hCrt = _open_osfhandle ((intptr_t) eif_conin, _O_TEXT | _O_RDONLY); #ifdef EIF_BORLAND dup2 (hCrt, _fileno(stdin)); #else hf = _fdopen (hCrt, "r"); *stdin = *hf; #endif } /* We are computing the cursor position to figure out, if the application * has been launched from a DOS console or from the Windows Shell */ GetConsoleScreenBufferInfo(eif_conout, &csbi); bLaunched = ((csbi.dwCursorPosition.X == 0) && (csbi.dwCursorPosition.Y == 0)); if ((csbi.dwSize.X <= 0) || (csbi.dwSize.Y <= 0)) bLaunched = FALSE; if (bLaunched == TRUE) eif_register_cleanup (eif_console_cleanup); eif_console_allocated = TRUE; } EIF_CONSOLE_UNLOCK; } }
void Screen::allocConsole() { int hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE *fp; // allocate a console for this app AllocConsole(); // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r" ); *stdin = *fp; setvbuf( stdin, NULL, _IONBF, 0 ); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stderr = *fp; setvbuf( stderr, NULL, _IONBF, 0 ); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well ios::sync_with_stdio(); }
FILE * __cdecl kpathsea_win32_popen (kpathsea kpse, const char *cmd, const char *fmode) { char mode[3]; STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; FILE *f = NULL; int fno, i; HANDLE child_in, child_out; HANDLE father_in, father_out; HANDLE father_in_dup, father_out_dup; HANDLE current_in, current_out; HANDLE current_pid; char *env_path; int binary_mode; char *new_cmd, *app_name = NULL; char *p, *q; struct _popen_elt *new_process; char pname[MAXPATHLEN], *fp; char *suffixes[] = { ".bat", ".cmd", ".com", ".exe", NULL }; char **s; BOOL go_on; /* We always use binary mode */ mode[0] = fmode[0]; mode[1] = 'b'; mode[2] = '\0'; /* We should look for the application name along the PATH, and decide to prepend "%COMSPEC% /c " or not to the command line. Do nothing for the moment. */ /* Another way to do that would be to try CreateProcess first without invoking cmd, and look at the error code. If it fails because of command not found, try to prepend "cmd /c" to the cmd line. */ /* Look for the application name */ for (p = (char *)cmd; *p && isspace(*p); p++); if (*p == '"') { q = ++p; while(*p && *p != '"') p++; if (*p == '\0') { fprintf(stderr, "popen: malformed command (\" not terminated)\n"); return NULL; } } else for (q = p; *p && !isspace(*p); p++); /* q points to the beginning of appname, p to the last + 1 char */ if ((app_name = malloc(p - q + 1)) == NULL) { fprintf(stderr, "xpopen: malloc(app_name) failed.\n"); return NULL; } strncpy(app_name, q, p - q ); app_name[p - q] = '\0'; pname[0] = '\0'; #ifdef TRACE fprintf(stderr, "popen: app_name = %s\n", app_name); #endif { char *tmp = getenv("PATH"); env_path = xmalloc(strlen(tmp) + 3); strcpy(env_path, tmp); strcat(env_path, ";."); } /* Looking for appname on the path */ for (s = suffixes, go_on = TRUE; go_on; *s++) { if (SearchPath(env_path, /* Address of search path */ app_name, /* Address of filename */ *s, /* Address of extension */ MAXPATHLEN, /* Size of destination buffer */ pname, /* Address of destination buffer */ &fp) /* File part of app_name */ != 0 && *s) { /* added *s in order not to allow no suffix. --ak 2009/10/24 */ #ifdef TRACE fprintf(stderr, "%s found with suffix %s\nin %s\n", app_name, *s, pname); #endif new_cmd = xstrdup(cmd); free(app_name); app_name = xstrdup(pname); break; } go_on = (*s != NULL); } if (go_on == FALSE) { /* the app_name was not found */ #ifdef TRACE fprintf(stderr, "%s not found, concatenating comspec\n", app_name); #endif new_cmd = concatn("cmd.exe", " /c ", cmd, NULL); free(app_name); app_name = NULL; } if (env_path) free(env_path); #ifdef TRACE fprintf(stderr, "popen: app_name = %s\n", app_name); fprintf(stderr, "popen: cmd_line = %s\n", new_cmd); #endif current_in = GetStdHandle(STD_INPUT_HANDLE); current_out = GetStdHandle(STD_OUTPUT_HANDLE); current_pid = GetCurrentProcess(); ZeroMemory( &si, sizeof(STARTUPINFO) ); si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; if (strchr(mode, 'b')) binary_mode = _O_BINARY; else binary_mode = _O_TEXT; /* Opening the pipe for writing */ if (strchr(mode, 'w')) { binary_mode |= _O_WRONLY; if (CreatePipe(&child_in, &father_out, &sa, 0) == FALSE) { fprintf(stderr, "popen: error CreatePipe\n"); return NULL; } si.hStdInput = child_in; si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); if (DuplicateHandle(current_pid, father_out, current_pid, &father_out_dup, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE) { fprintf(stderr, "popen: error DuplicateHandle father_out\n"); return NULL; } CloseHandle(father_out); fno = _open_osfhandle((long)father_out_dup, binary_mode); f = _fdopen(fno, mode); i = setvbuf( f, NULL, _IONBF, 0 ); } /* Opening the pipe for reading */ else if (strchr(mode, 'r')) { binary_mode |= _O_RDONLY; if (CreatePipe(&father_in, &child_out, &sa, 0) == FALSE) { fprintf(stderr, "popen: error CreatePipe\n"); return NULL; } si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = child_out; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); if (DuplicateHandle(current_pid, father_in, current_pid, &father_in_dup, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE) { fprintf(stderr, "popen: error DuplicateHandle father_in\n"); return NULL; } CloseHandle(father_in); fno = _open_osfhandle((long)father_in_dup, binary_mode); f = _fdopen(fno, mode); i = setvbuf( f, NULL, _IONBF, 0 ); } else { fprintf(stderr, "popen: invalid mode %s\n", mode); return NULL; } /* creating child process */ if (CreateProcess(app_name, /* pointer to name of executable module */ new_cmd, /* pointer to command line string */ NULL, /* pointer to process security attributes */ NULL, /* pointer to thread security attributes */ TRUE, /* handle inheritance flag */ 0, /* creation flags, do not touch this again ! (16/06/98) */ NULL, /* pointer to environment */ NULL, /* pointer to current directory */ &si, /* pointer to STARTUPINFO */ &pi /* pointer to PROCESS_INFORMATION */ ) == FALSE) { fprintf(stderr, "popen: CreateProcess %x\n", GetLastError()); return NULL; } /* Only the process handle is needed */ if (CloseHandle(pi.hThread) == FALSE) { fprintf(stderr, "popen: error closing thread handle\n"); return NULL; } if (new_cmd) free(new_cmd); if (app_name) free(app_name); /* Add the pair (f, pi.hProcess) to the list */ if ((new_process = malloc(sizeof(struct _popen_elt))) == NULL) { fprintf (stderr, "popen: malloc(new_process) error\n"); return NULL; } /* Saving the FILE * pointer, access key for retrieving the process handle later on */ new_process->f = f; /* Closing the unnecessary part of the pipe */ if (strchr(mode, 'r')) { CloseHandle(child_out); } else if (strchr(mode, 'w')) { CloseHandle(child_in); } /* Saving the process handle */ new_process->hp = pi.hProcess; /* Linking it to the list of popen() processes */ new_process->next = kpse->_popen_list; kpse->_popen_list = new_process; return f; }
bool LogFile::OpenLog(CString &sName, CCriticalSection *cs) { if (fLog) CloseLog(); sLogName = sName; lpCS = cs; CSingleLock singleLock (lpCS, TRUE); #if 0 HANDLE hLog = CreateFile((LPCTSTR)sLogName, GENERIC_READ|GENERIC_WRITE, 0, // share mode NULL, // security attributes OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hLog == INVALID_HANDLE_VALUE) { AfxMessageBox("Can't open log file", MB_ICONERROR); return false; } int fdLog = _open_osfhandle((intptr_t)hLog, _O_APPEND | _O_TEXT); if (fdLog == -1) { AfxMessageBox("Can't open log file", MB_ICONERROR); CloseHandle(hLog); return false; } fLog = _fdopen(fdLog, "a"); if (fLog == NULL) { #else if ((fLog =fopen((LPCTSTR)sLogName, "a")) == NULL) { #endif AfxMessageBox(_strerror("Warning! Can't open log file"), MB_ICONERROR); return (false); } return true; } bool LogFile::OpenLog (char *mode) { CSingleLock singleLock (lpCS, TRUE); // return if the log is already open if (fLog) return (true); #if 0 HANDLE hLog = CreateFile((LPCTSTR)sLogName, GENERIC_READ|GENERIC_WRITE, 0, // share mode NULL, // security attributes OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hLog == INVALID_HANDLE_VALUE) { AfxMessageBox("Can't open log file", MB_ICONERROR); return false; } int fdLog = _open_osfhandle((intptr_t)hLog, _O_APPEND | _O_TEXT); if (fdLog == -1) { AfxMessageBox("Can't open log file", MB_ICONERROR); CloseHandle(hLog); return false; } fLog = _fdopen(fdLog, "a"); if (fLog == NULL) { #else if ((fLog =fopen((LPCTSTR)sLogName, "a")) == NULL) { #endif AfxMessageBox(_strerror("Warning! Can't open log file"), MB_ICONERROR); return (false); } return true; } LogFile::~LogFile() { } void LogFile::EndLog() { Log ("This is the end !\n"); CloseLog(); }
// Setup the console for output (e.g. using printf) bool setup_console() { int hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE *fp; // create a console if (!AttachConsole(ATTACH_PARENT_PROCESS)) { // if no parent console then give up return false; } const unsigned int MAX_CONSOLE_LINES = 500; // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); if (!fp) { // could not open stdout return false; } *stdout = *fp; setvbuf(stdout, NULL, _IONBF, 0); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "r"); if (!fp) { // could not open stdin return false; } *stdin = *fp; setvbuf(stdin, NULL, _IONBF, 0); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); if (!fp) { // could not open stderr return false; } *stderr = *fp; setvbuf(stderr, NULL, _IONBF, 0); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well std::ios::sync_with_stdio(); return true; }
void OpenConsole() { COORD csize; CONSOLE_SCREEN_BUFFER_INFO csbiInfo; SMALL_RECT srect; char buf[256]; //dont do anything if we're already attached if (hConsole) return; //attach to an existing console (if we can; this is circuitous because AttachConsole wasnt added until XP) //remember to abstract this late bound function notion if we end up having to do this anywhere else bool attached = false; HMODULE lib = LoadLibrary("kernel32.dll"); if(lib) { typedef BOOL (WINAPI *_TAttachConsole)(DWORD dwProcessId); _TAttachConsole _AttachConsole = (_TAttachConsole)GetProcAddress(lib,"AttachConsole"); if(_AttachConsole) { if(_AttachConsole(-1)) attached = true; } FreeLibrary(lib); } //if we failed to attach, then alloc a new console if(!attached) { AllocConsole(); } hConsole = GetStdHandle(STD_OUTPUT_HANDLE); //redirect stdio long lStdHandle = (long)hConsole; int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); if(hConHandle == -1) return; //this fails from a visual studio command prompt FILE *fp = _fdopen( hConHandle, "w" ); *stdout = *fp; //and stderr *stderr = *fp; memset(buf,0,256); sprintf(buf,"%s OUTPUT", DESMUME_NAME_AND_VERSION); SetConsoleTitle(TEXT(buf)); csize.X = 60; csize.Y = 800; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csize); GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo); srect = csbiInfo.srWindow; srect.Right = srect.Left + 99; srect.Bottom = srect.Top + 64; SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &srect); SetConsoleCP(GetACP()); SetConsoleOutputCP(GetACP()); if(attached) printlog("\n"); printlog("%s\n",DESMUME_NAME_AND_VERSION); printlog("- compiled: %s %s\n\n",__DATE__,__TIME__); }
/****************************************************************************** Update a new GIF file, given its file handle. Returns dynamically allocated GifFileType pointer which serves as the GIF info record. ******************************************************************************/ GifFileType * DGifOpenFileHandle(int FileHandle, int *Error) { char Buf[GIF_STAMP_LEN + 1]; GifFileType *GifFile; GifFilePrivateType *Private; FILE *f; GifFile = (GifFileType *)malloc(sizeof(GifFileType)); if (GifFile == NULL) { if (Error != NULL) *Error = D_GIF_ERR_NOT_ENOUGH_MEM; (void)_close(FileHandle); return NULL; } /*@i1@*/memset(GifFile, '\0', sizeof(GifFileType)); /* Belt and suspenders, in case the null pointer isn't zero */ GifFile->SavedImages = NULL; GifFile->SColorMap = NULL; Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType)); if (Private == NULL) { if (Error != NULL) *Error = D_GIF_ERR_NOT_ENOUGH_MEM; (void)_close(FileHandle); free((char *)GifFile); return NULL; } #ifdef _WIN32 _setmode(FileHandle, O_BINARY); /* Make sure it is in binary mode. */ #endif /* _WIN32 */ f = _fdopen(FileHandle, "rb"); /* Make it into a stream: */ /*@-mustfreeonly@*/ GifFile->Private = (void *)Private; Private->FileHandle = FileHandle; Private->File = f; Private->FileState = FILE_STATE_READ; Private->Read = NULL; /* don't use alternate input method (TVT) */ GifFile->UserData = NULL; /* TVT */ /*@=mustfreeonly@*/ /* Let's see if this is a GIF file: */ /* coverity[check_return] */ if (READ(GifFile, (unsigned char *)Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) { if (Error != NULL) *Error = D_GIF_ERR_READ_FAILED; (void)fclose(f); free((char *)Private); free((char *)GifFile); return NULL; } /* Check for GIF prefix at start of file */ Buf[GIF_STAMP_LEN] = 0; if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) { if (Error != NULL) *Error = D_GIF_ERR_NOT_GIF_FILE; (void)fclose(f); free((char *)Private); free((char *)GifFile); return NULL; } if (DGifGetScreenDesc(GifFile) == GIF_ERROR) { (void)fclose(f); free((char *)Private); free((char *)GifFile); return NULL; } GifFile->Error = 0; /* What version of GIF? */ Private->gif89 = (Buf[GIF_VERSION_POS] == '9'); return GifFile; }
Window::Window(std::string title, int sizeX, int sizeY, bool fullScreen) { renderer = NULL; window = this; forceQuit = false; init = false; mouseLeftWindow = false; lockMouse = false; showMouse = true; this->fullScreen = fullScreen; size.x = (float)sizeX; size.y = (float)sizeY; fullScreen ? position.x = 0.0f : position.x = 100.0f; fullScreen ? position.y = 0.0f : position.y = 100.0f; HINSTANCE hInstance = GetModuleHandle( NULL ); //This creates the console window AllocConsole(); int consoleHandle; long stdHandle; FILE *file; // redirect stdout stdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); consoleHandle = _open_osfhandle(stdHandle, _O_TEXT); file = _fdopen( consoleHandle, "w" ); *stdout = *file; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect stdin stdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); file = _fdopen( consoleHandle, "r" ); *stdin = *file; setvbuf( stdin, NULL, _IONBF, 0 ); // WNDCLASSEX windowClass; ZeroMemory(&windowClass, sizeof(WNDCLASSEX)); if(!GetClassInfoEx(hInstance,WINDOWCLASS,&windowClass)) { windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_HREDRAW | CS_VREDRAW; windowClass.lpfnWndProc = (WNDPROC)WindowProc; windowClass.hInstance = hInstance; windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW; windowClass.lpszClassName = WINDOWCLASS; if(!RegisterClassEx(&windowClass)) { std::cout << "Window::Window(): Failed to register class!" << std::endl; return; } } if(fullScreen) { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = sizeX; // Selected Screen Width dmScreenSettings.dmPelsHeight = sizeY; // Selected Screen Height dmScreenSettings.dmBitsPerPel = 32; // Selected Bits Per Pixel dmScreenSettings.dmDisplayFrequency = 60; dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT|DM_DISPLAYFREQUENCY; if(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { std::cout << "Window::Window(): Failed to switch to fullscreen!" << std::endl; return; } } windowHandle = CreateWindowEx(fullScreen ? WS_EX_TOPMOST : NULL, WINDOWCLASS, // name of the window class title.c_str(), // title of the window fullScreen ? WS_POPUP|WS_VISIBLE : WS_OVERLAPPEDWINDOW|WS_POPUP|WS_VISIBLE|WS_SYSMENU|WS_MAXIMIZEBOX|WS_MINIMIZEBOX, // window style (int)position.x, // x-position of the window (int)position.y, // y-position of the window (int)size.x, // width of the window (int)size.y, // height of the window NULL, // No parent window! NULL, // No Menus! hInstance, // application handle NULL); // No multiple windows! if(!windowHandle) { std::cout << "Window::Window(): Failed to create window!" << std::endl; return; } if(!keyboard) { keyboard = new Keyboard(windowHandle); } if(!mouse) { mouse = new Mouse(windowHandle); } //if(!timer) { timer = new GameTimer(); //} elapsedMS = timer->GetMS(); Window::GetMouse()->SetAbsolutePositionBounds((unsigned int)size.x,(unsigned int)size.y); POINT pt; GetCursorPos(&pt); ScreenToClient(window->windowHandle, &pt); Window::GetMouse()->SetAbsolutePosition(pt.x,pt.y); LockMouseToWindow(lockMouse); ShowOSPointer(showMouse); init = true; }
/*! Initialised the airhockey game * * @param argc Number of commandl-ine arguments * @param args Command-line arguments * @returns ICRESULT Success/failure of initialization **/ ICRESULT SkeeBall::Init(int argc, char* args[]) { ICRESULT res = IC_OK; // Initialize SkeeBall Settings ProcessSettings(); HACK_FULLSCREEN = m_Settings.bWiiMote; #ifdef WIIMOTE if (m_Settings.bWiiMote) { // spawn console window and attache input/output streams AllocConsole(); console = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((long) console, _O_TEXT); FILE* hf_out = _fdopen(hCrt, "w"); setvbuf(hf_out, NULL, _IONBF, 1); *stdout = *hf_out; HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((long) handle_in, _O_TEXT); FILE* hf_in = _fdopen(hCrt, "r"); setvbuf(hf_in, NULL, _IONBF, 128); *stdin = *hf_in; } #endif // create the main window #if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) uint winFlags = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; //uint winFlags = WS_CAPTION ; //uint winFlags = WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; #elif defined __APPLE__ uint winFlags = kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowStandardHandlerAttribute ; //uint winFlags = kWindowNoTitleBarAttribute; #else uint winFlags = 0; #endif icWindowDef window = {winFlags, m_Settings.iScreen_x, m_Settings.iScreen_y, 0,0, "Skee Ball", m_Settings.bFullscreen }; m_pMainWin = icWindow::GetWindow(window); // create the graphics device m_pGxDevice = new icGXDeviceGL(); // check that we got the goods if (!m_pMainWin || !m_pGxDevice) { #ifdef DEBUG_INSTALL MessageBoxA(0,"Failed to window or engine", "Error", 0); #endif return IC_FAIL_GEN; } // initialize the graphics device m_pGxDevice->Init(m_pMainWin); //m_pGxDevice->EnableFog(m_Settings.bFog, m_Settings.fogParams); // Set the clear color to black ((icGXDeviceGL*)m_pGxDevice)->SetClearColor(icColor::BLACK); // show the main window m_pMainWin->Show(); // initialize the sound engine res = m_SoundDevice.Initialize(); if (ICEFAIL(res)) { #ifdef DEBUG_INSTALL MessageBoxA(0,"Failed to init audio device", "Error", 0); #endif return res; } // Initialize the content manager m_Content = new icContentLoader(m_pGxDevice, &m_SoundDevice); icSoundParam params; params.bPaused = false; params.fPitch = 1.0f; params.bLoop = true; params.fVol = m_Settings.fMusic_vol; m_Content->Load("Resource/audio/01castlevania.wav",&m_BackGroundMusic); m_BackGroundMusic->SetParams(params); // start the background music if (m_Settings.bMusic) m_BackGroundMusic->Play(); if (ICEFAIL(res)) { #ifdef DEBUG_INSTALL MessageBoxA(0,"some other shit failed", "Error", 0); #endif return res; } // push the main menu (TODO, goes to gamestate right now) m_GameState.Init(m_Content); m_MainMenu.Init(m_Content); m_SettingsMenu.Init(m_Content); m_PauseMenu.Init(m_Content); m_LastGame.Init(m_Content); m_StateMachine.PushState(&m_LastGame); m_StateMachine.PushState(&m_MainMenu); // start keeping time m_GameTime.Elapsed(); m_font.Initialize("Arial",24,m_Content->GetDevice()); playing = true; #ifdef WIIMOTE if (m_Settings.bWiiMote) { icThreadCreate<SkeeBall>(this,&SkeeBall::WiiMoteLoop,NULL,&m_pthread); } #endif if (!ICEFAIL(res)) return icApplication::Init(argc,args); return res; }// END FUNCTION Init(int argc, char* args[])
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { MSG msg = { 0 }; window = InitWindow(hInstance); //1. Skapa fönster AllocConsole(); HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((long)handle_out, _O_TEXT); FILE* hf_out = _fdopen(hCrt, "w"); setvbuf(hf_out, NULL, _IONBF, 1); *stdout = *hf_out; HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((long)handle_in, _O_TEXT); FILE* hf_in = _fdopen(hCrt, "r"); setvbuf(hf_in, NULL, _IONBF, 128); *stdin = *hf_in; if (window) { HDC hDC = GetDC(window); HGLRC hRC = CreateOpenGLContext(window); //2. Skapa och koppla OpenGL context glewInit(); //3. Initiera The OpenGL Extension Wrangler Library (GLEW) //glEnable(GL_CULL_FACE); SetViewport(); //4. Sätt viewport ShowWindow(window, nCmdShow); state = new Menu(); buttonState = luaL_newstate(); luaL_openlibs(buttonState); if (luaL_loadfile(buttonState, "Error.lua") || lua_pcall(buttonState, 0, 0, 0)) { std::cout << "Error handler failed" << std::endl; std::cerr << lua_tostring(buttonState, -1) << std::endl; lua_pop(buttonState, 1); } lua_getglobal(buttonState, "ErrorHandler"); int luaErrorHandlerPos = lua_gettop(buttonState); registerLuaFuncs(); if (luaL_loadfile(buttonState, "menuButtons.txt") || lua_pcall(buttonState, 0, 0, luaErrorHandlerPos)) { std::cout << "erroooor" << std::endl; std::cout << lua_tostring(buttonState, -1) << std::endl; lua_pop(buttonState, 1); } setupButtons(); lua_pop(buttonState, 1); while (WM_QUIT != msg.message) { if (msg.message == WM_LBUTTONDOWN) clickUpdate(); if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { Update(); //9. Rendera SwapBuffers(hDC); //10. Växla front- och back-buffer } } wglMakeCurrent(NULL, NULL); ReleaseDC(window, hDC); wglDeleteContext(hRC); DestroyWindow(window); } lua_close(buttonState); return (int)msg.wParam; }
void __stdcall service_main_fn(DWORD argc, LPTSTR *argv) { HANDLE hCurrentProcess; HANDLE hPipeRead = NULL; HANDLE hPipeReadDup; HANDLE hNullFile; DWORD threadid; SECURITY_ATTRIBUTES sa = {0}; char **newargv; if(!(globdat.hServiceStatus = RegisterServiceCtrlHandler(argv[0], service_ctrl))) { ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL, "Failure registering service handler"); return; } ReportStatusToSCMgr( SERVICE_START_PENDING, // service state NO_ERROR, // exit code 3000); // wait hint /* Create a pipe to send stderr messages to the system error log */ hCurrentProcess = GetCurrentProcess(); if (CreatePipe(&hPipeRead, &eventlog_pipewrite, &sa, 0)) { if (DuplicateHandle(hCurrentProcess, hPipeRead, hCurrentProcess, &hPipeReadDup, 0, FALSE, DUPLICATE_SAME_ACCESS)) { CloseHandle(hPipeRead); hPipeRead = hPipeReadDup; eventlog_thread = CreateThread(NULL, 0, service_stderr_thread, (LPVOID) hPipeRead, 0, &threadid); if (eventlog_thread) { int fh; FILE *fl; fflush(stderr); SetStdHandle(STD_ERROR_HANDLE, eventlog_pipewrite); fh = _open_osfhandle((long) STD_ERROR_HANDLE, _O_WRONLY | _O_BINARY); dup2(fh, STDERR_FILENO); fl = _fdopen(STDERR_FILENO, "wcb"); memcpy(stderr, fl, sizeof(FILE)); } else { CloseHandle(hPipeRead); CloseHandle(eventlog_pipewrite); eventlog_pipewrite = NULL; } } else { CloseHandle(hPipeRead); CloseHandle(eventlog_pipewrite); eventlog_pipewrite = NULL; } } /* Open a null handle to nak our stdin */ hNullFile = CreateFile("nul", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL); if (hNullFile == INVALID_HANDLE_VALUE) { ap_log_error(APLOG_MARK, APLOG_WIN32ERROR | APLOG_CRIT, NULL, "Parent: Unable to create null stdin pipe for this service process.\n"); } else { int fh; FILE *fl; fflush(stdin); SetStdHandle(STD_INPUT_HANDLE, hNullFile); fh = _open_osfhandle((long) STD_INPUT_HANDLE, _O_RDONLY | _O_BINARY); dup2(fh, STDIN_FILENO); fl = _fdopen(STDIN_FILENO, "rcb"); memcpy(stdin, fl, sizeof(FILE)); } /* Open a null handle to soak our stdout */ hNullFile = CreateFile("nul", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL); if (hNullFile == INVALID_HANDLE_VALUE) { ap_log_error(APLOG_MARK, APLOG_WIN32ERROR | APLOG_CRIT, NULL, "Parent: Unable to create null stdout pipe for this service process.\n"); } else { int fh; FILE *fl; fflush(stdout); SetStdHandle(STD_OUTPUT_HANDLE, hNullFile); fh = _open_osfhandle((long) STD_OUTPUT_HANDLE, _O_WRONLY | _O_BINARY); dup2(fh, STDOUT_FILENO); fl = _fdopen(STDOUT_FILENO, "wcb"); memcpy(stdout, fl, sizeof(FILE)); } /* Grab it or lose it */ globdat.name = argv[0]; ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, NULL, "Hooked up the Service Error Event Logger."); /* Fold the "Start Parameters" in with the true executable argv[0], * and insert a -n tag to pass the service name from the SCM's argv[0] */ newargv = (char**) malloc((argc + 3) * sizeof(char*)); newargv[0] = ap_server_argv0; /* The true executable name */ newargv[1] = "-n"; /* True service name follows (argv[0]) */ memcpy (newargv + 2, argv, argc * sizeof(char*)); newargv[argc + 2] = NULL; /* SCM doesn't null terminate the array */ argv = newargv; argc += 2; /* Use the name of the service as the error log marker */ ap_server_argv0 = globdat.name; globdat.exit_status = globdat.main_fn( argc, argv ); }
/* * Main application routine. * * Nut/OS automatically calls this entry after initialization. */ int main(void) { TCPSOCKET *sock; CHANNEL cd; uint32_t baud = 9600; /* * Register our devices. */ NutRegisterDevice(&DEV_UART, 0, 0); #ifndef DEV_ETHER for (;;); #else NutRegisterDevice(&DEV_ETHER, 0x8300, 5); /* * Setup the uart device. */ cd.cd_rs232 = fopen(DEV_UART_NAME, "r+b"); _ioctl(_fileno(cd.cd_rs232), UART_SETSPEED, &baud); /* * Setup the ethernet device. Try DHCP first. If this is * the first time boot with empty EEPROM and no DHCP server * was found, use hardcoded values. */ if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000)) { /* No valid EEPROM contents, use hard coded MAC. */ uint8_t my_mac[] = { 0x00, 0x06, 0x98, 0x20, 0x00, 0x00 }; if (NutDhcpIfConfig("eth0", my_mac, 60000)) { /* No DHCP server found, use hard coded IP address. */ uint32_t ip_addr = inet_addr("192.168.192.100"); uint32_t ip_mask = inet_addr("255.255.255.0"); NutNetIfConfig("eth0", my_mac, ip_addr, ip_mask); /* If not in a local network, we must also call NutIpRouteAdd() to configure the routing. */ } } /* * Start a RS232 receiver thread. */ NutThreadCreate("xmit", Receiver, &cd, 512); /* * Now loop endless for connections. */ cd.cd_connected = 0; for (;;) { /* * Create a socket and listen for a client. */ sock = NutTcpCreateSocket(); NutTcpAccept(sock, TCPPORT); /* * Open a stdio stream assigned to the connected socket. */ cd.cd_tcpip = _fdopen((int) sock, "r+b"); cd.cd_connected = 1; /* * Call RS232 transmit routine. On return we will be * disconnected again. */ StreamCopy(cd.cd_tcpip, cd.cd_rs232, &cd.cd_connected); /* * Close the stream. */ fclose(cd.cd_tcpip); /* * Close our socket. */ NutTcpCloseSocket(sock); } #endif return 0; }
FILE * PipeSpawn( char* cmdstring, void* localEnvVars ) { int PipeHandle[2]; HANDLE WriteHandle, ErrorHandle; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInformation; BOOL Status; FILE* pstream; ASSERT(cmdstring != NULL); // Open the pipe where we'll collect the output. _pipe(PipeHandle, 20 * 1024, _O_TEXT|_O_NOINHERIT); // 20K bytes buffer DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(PipeHandle[1]), GetCurrentProcess(), &WriteHandle, 0L, TRUE, DUPLICATE_SAME_ACCESS); DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(PipeHandle[1]), GetCurrentProcess(), &ErrorHandle, 0L, TRUE, DUPLICATE_SAME_ACCESS); _close(PipeHandle[1]); pstream = _fdopen(PipeHandle[0], "rt"); if (pstream == NULL) { LogError("Creation of I/O filter stream failed - error = %d\n", cmdstring, errno); CloseHandle(WriteHandle); CloseHandle(ErrorHandle); WriteHandle = INVALID_HANDLE_VALUE; ErrorHandle = INVALID_HANDLE_VALUE; _close(PipeHandle[0]); return NULL; } memset(&StartupInfo, 0, sizeof(STARTUPINFO)); StartupInfo.cb = sizeof(STARTUPINFO); StartupInfo.hStdOutput = WriteHandle; StartupInfo.hStdError = ErrorHandle; StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); StartupInfo.dwFlags = STARTF_USESTDHANDLES; memset(&ProcessInformation, 0, sizeof(PROCESS_INFORMATION)); ProcessInformation.hThread = INVALID_HANDLE_VALUE; ProcessInformation.hProcess = INVALID_HANDLE_VALUE; // And start the process. #ifndef NODEBUG if (FDebug) { printf("Creating process '%s'\n", cmdstring); fflush(stdout); } #endif Status = CreateProcess(NULL, cmdstring, NULL, NULL, TRUE, 0, localEnvVars, NULL, &StartupInfo, &ProcessInformation); CloseHandle(WriteHandle); CloseHandle(ErrorHandle); WriteHandle = INVALID_HANDLE_VALUE; ErrorHandle = INVALID_HANDLE_VALUE; if (Status == 0) { LogError("Exec of '%s' failed - error = %d\n", cmdstring, GetLastError()); fclose(pstream); // This will close the read handle pstream = NULL; ProcHandle = INVALID_HANDLE_VALUE; } else { CloseHandle(ProcessInformation.hThread); ProcessInformation.hThread = INVALID_HANDLE_VALUE; ProcHandle = ProcessInformation.hProcess; } return pstream; }
void redirect_stdout_stderr (const char *file, bool append) { #if defined(WIN32) if (!std_redir) { struct gc_arena gc = gc_new (); HANDLE log_handle; int log_fd; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; log_handle = CreateFileW (wide_string (file, &gc), GENERIC_WRITE, FILE_SHARE_READ, &saAttr, append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); gc_free (&gc); if (log_handle == INVALID_HANDLE_VALUE) { msg (M_WARN|M_ERRNO, "Warning: cannot open --log file: %s", file); return; } /* append to logfile? */ if (append) { if (SetFilePointer (log_handle, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER) msg (M_ERR, "Error: cannot seek to end of --log file: %s", file); } /* save original stderr for password prompts */ orig_stderr = GetStdHandle (STD_ERROR_HANDLE); #if 0 /* seems not be necessary with stdout/stderr redirection below*/ /* set up for redirection */ if (!SetStdHandle (STD_OUTPUT_HANDLE, log_handle) || !SetStdHandle (STD_ERROR_HANDLE, log_handle)) msg (M_ERR, "Error: cannot redirect stdout/stderr to --log file: %s", file); #endif /* direct stdout/stderr to point to log_handle */ log_fd = _open_osfhandle ((intptr_t)log_handle, _O_TEXT); if (log_fd == -1) msg (M_ERR, "Error: --log redirect failed due to _open_osfhandle failure"); /* open log_handle as FILE stream */ ASSERT (msgfp == NULL); msgfp = _fdopen (log_fd, "wt"); if (msgfp == NULL) msg (M_ERR, "Error: --log redirect failed due to _fdopen"); /* redirect C-library stdout/stderr to log file */ if (_dup2 (log_fd, 1) == -1 || _dup2 (log_fd, 2) == -1) msg (M_WARN, "Error: --log redirect of stdout/stderr failed"); std_redir = true; } #elif defined(HAVE_DUP2) if (!std_redir) { int out = open (file, O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC), S_IRUSR | S_IWUSR); if (out < 0) { msg (M_WARN|M_ERRNO, "Warning: Error redirecting stdout/stderr to --log file: %s", file); return; } if (dup2 (out, 1) == -1) msg (M_ERR, "--log file redirection error on stdout"); if (dup2 (out, 2) == -1) msg (M_ERR, "--log file redirection error on stderr"); if (out > 2) close (out); std_redir = true; } #else msg (M_WARN, "WARNING: The --log option is not supported on this OS because it lacks the dup2 function"); #endif }
static FILE *JsiFdOpenForRead(fdtype fd) { return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r"); }
FILE * pt_popen(const char *cmd, const char *mode) { FILE *fptr = NULL; PROCESS_INFORMATION piProcInfo; STARTUPINFOW siStartInfo; int success, redirect_error = 0; wchar_t *wcmd = NULL; wchar_t *err2out; pipe_context *pc; size_t utf8len = utf8_strlen(cmd, strlen(cmd)); if ( !(wcmd = malloc((utf8len+1)*sizeof(wchar_t))) ) { return NULL; } utf8towcs(wcmd, cmd); if ( !(pc=allocPipeContext()) ) goto finito; if ( !mode || !*mode ) goto finito; pc->mode = *mode; if ( pc->mode != 'r' && pc->mode != 'w' ) goto finito; /* * Shall we redirect stderr to stdout ? */ if ( (err2out=wcsstr(wcmd, L"2>&1")) != NULL) { /* this option doesn't apply to win32 shells, so we clear it out! */ wcsncpy(err2out, L" ", 4); redirect_error = 1; } /* * Create the Pipes... */ if (my_pipe(pc->in) == -1 || my_pipe(pc->out) == -1) goto finito; if ( !redirect_error ) { if ( my_pipe(pc->err) == -1) goto finito; } /* * Now create the child process */ ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdInput = pc->in[0]; siStartInfo.hStdOutput = pc->out[1]; if ( redirect_error ) siStartInfo.hStdError = pc->out[1]; else siStartInfo.hStdError = pc->err[1]; siStartInfo.dwFlags = STARTF_USESTDHANDLES; success = CreateProcessW(NULL, wcmd, // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited CREATE_NO_WINDOW, // creation flags: without window (?) NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION if ( !success ) goto finito; CloseHandle(piProcInfo.hThread); CloseHandle(piProcInfo.hProcess); /* * These handles listen to the Child process */ CloseHandle(pc->in[0]); pc->in[0] = INVALID_HANDLE_VALUE; CloseHandle(pc->out[1]); pc->out[1] = INVALID_HANDLE_VALUE; if ( pc->err[1] != INVALID_HANDLE_VALUE ) { CloseHandle(pc->err[1]); pc->err[1] = INVALID_HANDLE_VALUE; } if ( pc->mode == 'r' ) fptr = _fdopen(_open_osfhandle((intptr_t)pc->out[0],_O_BINARY),"r"); else fptr = _fdopen(_open_osfhandle((intptr_t)pc->in[1],_O_BINARY),"w"); finito: if ( fptr ) { pc->fd = fptr; linkPipeContext(pc); } else { if ( pc ) discardPipeContext(pc); } if ( wcmd ) free(wcmd); return fptr; }
static FILE *JsiFdOpenForWrite(fdtype fd) { return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w"); }
/* * Open a stdio stream, handling special filenames */ FILE *zopen(const char *name, const char *mode) { char command[MAXPATHLEN + 100]; if (stdio_filename_p(name)) { /* * Return stream to stdin or stdout */ if (*mode == 'r') { static int stdin_used = 0; static int stdin_warning = 0; int fd; if (stdin_used) { if (!stdin_warning) { fprintf(stderr, "warning: '-' used multiple times for input\n"); stdin_warning = 1; } } else { stdin_used = 1; } #ifdef _MSC_VER fd = _dup(0); return fd < 0 ? NULL : _fdopen(fd, mode); #else fd = dup(0); return fd < 0 ? NULL : fdopen(fd, mode); #endif } else if (*mode == 'w' || *mode == 'a') { static int stdout_used = 0; static int stdout_warning = 0; int fd; if (stdout_used) { if (!stdout_warning) { fprintf(stderr, "warning: '-' used multiple times for output\n"); stdout_warning = 1; } } else { stdout_used = 1; } #ifdef _MSC_VER fd = _dup(1); return fd < 0 ? NULL : _fdopen(fd, mode); #else fd = dup(1); return fd < 0 ? NULL : fdopen(fd, mode); #endif } else { return NULL; } } else { char *compress_cmd = NULL; char *uncompress_cmd = NULL; int zip_to_stdout = 1; if (compressed_filename_p(name)) { compress_cmd = COMPRESS_CMD; uncompress_cmd = UNCOMPRESS_CMD; } else if (gzipped_filename_p(name)) { compress_cmd = GZIP_CMD; uncompress_cmd = GUNZIP_CMD; } else if (bzipped_filename_p(name)) { compress_cmd = BZIP2_CMD; uncompress_cmd = BUNZIP2_CMD; } else if (sevenzipped_filename_p(name)) { compress_cmd = SEVENZIP_CMD; uncompress_cmd = SEVENUNZIP_CMD; zip_to_stdout = 0; } else if (xz_filename_p(name)) { compress_cmd = XZ_CMD; uncompress_cmd = XZ_DECOMPRESS_CMD; } if (compress_cmd != NULL) { #ifdef NO_ZIO fprintf(stderr, "Sorry, compressed I/O not available on this machine\n"); errno = EINVAL; return NULL; #else /* !NO_ZIO */ /* * Return stream to compress pipe */ if (*mode == 'r') { if (!readable_p(name)) return NULL; sprintf(command, "%s;%s %s", STD_PATH, uncompress_cmd, name); return popen(command, mode); } else if (*mode == 'w') { if (!writable_p(name)) return NULL; if (zip_to_stdout) { sprintf(command, "%s;%s >%s", STD_PATH, compress_cmd, name); } else { /* * This is necessary because the compression program might * complain if a zero-length file already exists. * However, it means that existing file owner & permission * attributes are not preserved. */ unlink(name); sprintf(command, "%s;%s %s", STD_PATH, compress_cmd, name); } return popen(command, mode); } else { return NULL; } #endif /* !NO_ZIO */ } else { return fopen(name, mode); } } }
bool rotate() { if ( ! _enabled ) { cout << "LoggingManager not enabled" << endl; return true; } if ( _file ) { #ifdef POSIX_FADV_DONTNEED posix_fadvise(fileno(_file), 0, 0, POSIX_FADV_DONTNEED); #endif // Rename the (open) existing log file to a timestamped name stringstream ss; ss << _path << "." << terseCurrentTime( false ); string s = ss.str(); if (0 != rename(_path.c_str(), s.c_str())) { error() << "Failed to rename " << _path << " to " << s; return false; } } FILE* tmp = 0; // The new file using the original logpath name #if _WIN32 // We rename an open log file (above, on next rotation) and the trick to getting Windows to do that is // to open the file with FILE_SHARE_DELETE. So, we can't use the freopen() call that non-Windows // versions use because it would open the file without the FILE_SHARE_DELETE flag we need. // HANDLE newFileHandle = CreateFileA( _path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if ( INVALID_HANDLE_VALUE != newFileHandle ) { int newFileDescriptor = _open_osfhandle( reinterpret_cast<intptr_t>(newFileHandle), _O_APPEND ); tmp = _fdopen( newFileDescriptor, _append ? "a" : "w" ); } #else tmp = freopen(_path.c_str(), _append ? "a" : "w", stdout); #endif if ( !tmp ) { cerr << "can't open: " << _path.c_str() << " for log file" << endl; return false; } // redirect stdout and stderr to log file dup2( fileno( tmp ), 1 ); // stdout dup2( fileno( tmp ), 2 ); // stderr Logstream::setLogFile(tmp); // after this point no thread will be using old file #if _WIN32 if ( _file ) fclose( _file ); // In Windows, we still have the old file open, close it now #endif #if 0 // enable to test redirection cout << "written to cout" << endl; cerr << "written to cerr" << endl; log() << "written to log()" << endl; #endif _file = tmp; // Save new file for next rotation return true; }
int send_message(u_long ip, u_short port, u_long *metaint){ int rc; FILE *stream; u_char *line; u_char *cp; TCPSOCKET *sock; u_long baud = DBG_BAUDRATE; // u_long radio_ip = inet_addr(RADIO_IPADDR); u_short tcpbufsiz = TCPIP_BUFSIZ; u_long rx_to = TCPIP_READTIMEOUT; u_short mss = TCPIP_MSS; puts("create a TCP socket"); /* * Create a TCP socket. */ if ((sock = NutTcpCreateSocket()) == 0) { puts("Error: Can't create socket"); for (; ;); } puts("set socket options"); /* * Set socket options. Failures are ignored. */ if (NutTcpSetSockOpt(sock, TCP_MAXSEG, &mss, sizeof(mss))) printf("Sockopt MSS failed\n"); if (NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to))) printf("Sockopt TO failed\n"); if (NutTcpSetSockOpt(sock, SO_RCVBUF, &tcpbufsiz, sizeof(tcpbufsiz))) printf("Sockopt rxbuf failed\n"); /* * Connect the TCP server. */ printf("Connecting %s:%u...","83.128.250.123" , 8080); if ((rc = NutTcpConnect(sock, inet_addr("83.128.250.123"), 8080))) { printf("Error: Connect failed with %d\n", NutTcpError(sock)); return 0; } puts("OK"); if ((stream = _fdopen((int) sock, "r+b")) == 0) { puts("Error: Can't create stream"); return 0; } /* * Send the HTTP request. */ printf("GET %s HTTP/1.0\n\n", "/api/telegram"); fprintf(stream, "GET %s HTTP/1.0\r\n", "/api/telegram"); fprintf(stream, "Host: %s\r\n", "83.128.250.123"); fprintf(stream, "User-Agent: Ethernut\r\n"); fprintf(stream, "Accept: */*\r\n"); fprintf(stream, "Connection: close\r\n"); fputs("\r\n", stream); fflush(stream); /* * Receive the HTTP header. */ line = malloc(MAX_HEADERLINE); while (fgets(line, MAX_HEADERLINE, stream)) { /* * Chop off the carriage return at the end of the line. If none * was found, then this line was probably too large for our buffer. */ cp = strchr(line, '\r'); if (cp == 0) { puts("Warning: Input buffer overflow"); continue; } *cp = 0; /* * The header is terminated by an empty line. */ if (*line == 0) { break; } printf("%s\n", line); } putchar('\n'); free(line); return 0; }
/*---------------------------------------------------------------------------- Replacement for 'popen()' under WIN32. NOTE: if cmd contains '2>&1', we connect the standard error file handle to the standard output file handle. ----------------------------------------------------------------------------*/ FILE * pt_popen(const char *cmd, const char *mode) { FILE *fptr = (FILE *)0; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; int success, umlenkung; my_pipein[0] = INVALID_HANDLE_VALUE; my_pipein[1] = INVALID_HANDLE_VALUE; my_pipeout[0] = INVALID_HANDLE_VALUE; my_pipeout[1] = INVALID_HANDLE_VALUE; my_pipeerr[0] = INVALID_HANDLE_VALUE; my_pipeerr[1] = INVALID_HANDLE_VALUE; if (!mode || !*mode) goto finito; my_popenmode = *mode; if (my_popenmode != 'r' && my_popenmode != 'w') goto finito; /* * Shall we redirect stderr to stdout ? */ umlenkung = strstr("2>&1",(char *)cmd) != 0; /* * Create the Pipes... */ if (my_pipe(my_pipein) == -1 || my_pipe(my_pipeout) == -1) goto finito; if (!umlenkung && my_pipe(my_pipeerr) == -1) goto finito; /* * Now create the child process */ ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdInput = my_pipein[0]; siStartInfo.hStdOutput = my_pipeout[1]; if (umlenkung) siStartInfo.hStdError = my_pipeout[1]; else siStartInfo.hStdError = my_pipeerr[1]; siStartInfo.dwFlags = STARTF_USESTDHANDLES; success = CreateProcess(NULL, (LPTSTR)cmd, // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited DETACHED_PROCESS, // creation flags: without window (?) NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION if (!success) goto finito; /* * These handles listen to the child process */ CloseHandle(my_pipein[0]); my_pipein[0] = INVALID_HANDLE_VALUE; CloseHandle(my_pipeout[1]); my_pipeout[1] = INVALID_HANDLE_VALUE; CloseHandle(my_pipeerr[1]); my_pipeerr[1] = INVALID_HANDLE_VALUE; if (my_popenmode == 'r') fptr = _fdopen(_open_osfhandle((long)my_pipeout[0],_O_BINARY),"r"); else fptr = _fdopen(_open_osfhandle((long)my_pipein[1],_O_BINARY),"w"); finito: if (!fptr) { if (my_pipein[0] != INVALID_HANDLE_VALUE) CloseHandle(my_pipein[0]); if (my_pipein[1] != INVALID_HANDLE_VALUE) CloseHandle(my_pipein[1]); if (my_pipeout[0] != INVALID_HANDLE_VALUE) CloseHandle(my_pipeout[0]); if (my_pipeout[1] != INVALID_HANDLE_VALUE) CloseHandle(my_pipeout[1]); if (my_pipeerr[0] != INVALID_HANDLE_VALUE) CloseHandle(my_pipeerr[0]); if (my_pipeerr[1] != INVALID_HANDLE_VALUE) CloseHandle(my_pipeerr[1]); } return fptr; }
/* A replacement for tmpfile, since the MSVCRT implementation creates the file in the root directory of the current drive, which might not be writable by our user. Most of the code borrowed from create_batch_file, see job.c. */ FILE * tmpfile (void) { char temp_path[MAXPATHLEN]; unsigned path_size = GetTempPath (sizeof temp_path, temp_path); int path_is_dot = 0; /* The following variable is static so we won't try to reuse a name that was generated a little while ago, because that file might not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below, which tells the OS it doesn't need to flush the cache to disk. If the file is not yet on disk, we might think the name is available, while it really isn't. This happens in parallel builds, where Make doesn't wait for one job to finish before it launches the next one. */ static unsigned uniq = 0; static int second_loop = 0; const char base[] = "gmake_tmpf"; const unsigned sizemax = sizeof base - 1 + 4 + 10 + 10; unsigned pid = GetCurrentProcessId (); if (path_size == 0) { path_size = GetCurrentDirectory (sizeof temp_path, temp_path); path_is_dot = 1; } ++uniq; if (uniq >= 0x10000 && !second_loop) { /* If we already had 64K batch files in this process, make a second loop through the numbers, looking for free slots, i.e. files that were deleted in the meantime. */ second_loop = 1; uniq = 1; } while (path_size > 0 && path_size + sizemax < sizeof temp_path && !(uniq >= 0x10000 && second_loop)) { HANDLE h; sprintf (temp_path + path_size, "%s%s%u-%x.tmp", temp_path[path_size - 1] == '\\' ? "" : "\\", base, pid, uniq); h = CreateFile (temp_path, /* file name */ GENERIC_READ | GENERIC_WRITE | DELETE, /* desired access */ FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */ NULL, /* default security attributes */ CREATE_NEW, /* creation disposition */ FILE_ATTRIBUTE_NORMAL | /* flags and attributes */ FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); /* no template file */ if (h == INVALID_HANDLE_VALUE) { const DWORD er = GetLastError (); if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS) { ++uniq; if (uniq == 0x10000 && !second_loop) { second_loop = 1; uniq = 1; } } /* The temporary path is not guaranteed to exist, or might not be writable by user. Use the current directory as fallback. */ else if (path_is_dot == 0) { path_size = GetCurrentDirectory (sizeof temp_path, temp_path); path_is_dot = 1; } else { errno = EACCES; break; } } else { int fd = _open_osfhandle ((intptr_t)h, 0); return _fdopen (fd, "w+b"); } } if (uniq >= 0x10000) errno = EEXIST; return NULL; }
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd) { CONTEXT("WinMain()"); BOOL any_desktop_running = IsAnyDesktopRunning(); BOOL startup_desktop; // strip extended options from the front of the command line String ext_options; while(*lpCmdLine == '-') { while(*lpCmdLine && !_istspace((unsigned)*lpCmdLine)) ext_options += *lpCmdLine++; while(_istspace((unsigned)*lpCmdLine)) ++lpCmdLine; } // command line option "-install" to replace previous shell application with ROS Explorer if (_tcsstr(ext_options,TEXT("-install"))) { // install ROS Explorer into the registry TCHAR path[MAX_PATH]; int l = GetModuleFileName(0, path, COUNTOF(path)); if (l) { HKEY hkey; if (!RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) { ///@todo save previous shell application in config file RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)path, l*sizeof(TCHAR)); RegCloseKey(hkey); } if (!RegOpenKey(HKEY_CURRENT_USER, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) { ///@todo save previous shell application in config file RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)TEXT(""), l*sizeof(TCHAR)); RegCloseKey(hkey); } } HWND shellWindow = GetShellWindow(); if (shellWindow) { DWORD pid; // terminate shell process for NT like systems GetWindowThreadProcessId(shellWindow, &pid); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); // On Win 9x it's sufficient to destroy the shell window. DestroyWindow(shellWindow); if (TerminateProcess(hProcess, 0)) WaitForSingleObject(hProcess, INFINITE); CloseHandle(hProcess); } startup_desktop = TRUE; } else { // create desktop window and task bar only, if there is no other shell and we are // the first explorer instance // MS Explorer looks additionally into the registry entry HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\shell, // to decide wether it is currently configured as shell application. startup_desktop = !any_desktop_running; } bool autostart = !any_desktop_running; // disable autostart if the SHIFT key is pressed if (GetAsyncKeyState(VK_SHIFT) < 0) autostart = false; #ifdef _DEBUG //MF: disabled for debugging autostart = false; #endif // If there is given the command line option "-desktop", create desktop window anyways if (_tcsstr(ext_options,TEXT("-desktop"))) startup_desktop = TRUE; #ifndef ROSSHELL else if (_tcsstr(ext_options,TEXT("-nodesktop"))) startup_desktop = FALSE; // Don't display cabinet window in desktop mode if (startup_desktop && !_tcsstr(ext_options,TEXT("-explorer"))) nShowCmd = SW_HIDE; #endif if (_tcsstr(ext_options,TEXT("-noautostart"))) autostart = false; else if (_tcsstr(ext_options,TEXT("-autostart"))) autostart = true; #ifndef __WINE__ if (_tcsstr(ext_options,TEXT("-console"))) { AllocConsole(); _dup2(_open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_RDONLY), 0); _dup2(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0), 1); _dup2(_open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), 0), 2); g_Globals._log = _fdopen(1, "w"); setvbuf(g_Globals._log, 0, _IONBF, 0); LOG(TEXT("starting explorer debug log\n")); } #endif if (startup_desktop) { // hide the XP login screen (Credit to Nicolas Escuder) // another undocumented event: "Global\\msgina: ReturnToWelcome" if (!SetShellReadyEvent(TEXT("msgina: ShellReadyEvent"))) SetShellReadyEvent(TEXT("Global\\msgina: ShellReadyEvent")); } #ifdef ROSSHELL else return 0; // no shell to launch, so exit immediatelly #endif if (!any_desktop_running) { // launch the shell DDE server if (g_SHDOCVW_ShellDDEInit) (*g_SHDOCVW_ShellDDEInit)(TRUE); } bool use_gdb_stub = false; // !IsDebuggerPresent(); if (_tcsstr(ext_options,TEXT("-debug"))) use_gdb_stub = true; if (_tcsstr(ext_options,TEXT("-break"))) { LOG(TEXT("debugger breakpoint")); __debugbreak(); } #ifdef _M_IX86 // activate GDB remote debugging stub if no other debugger is running if (use_gdb_stub) { LOG(TEXT("waiting for debugger connection...\n")); initialize_gdb_stub(); } #endif g_Globals.init(hInstance); // initialize COM and OLE before creating the desktop window OleInit usingCOM; // init common controls library CommonControlInit usingCmnCtrl; g_Globals.read_persistent(); if (startup_desktop) { WaitCursor wait; g_Globals._desktops.init(); g_Globals._hwndDesktop = DesktopWindow::Create(); #ifdef _USE_HDESK g_Globals._desktops.get_current_Desktop()->_hwndDesktop = g_Globals._hwndDesktop; #endif } if (_tcsstr(ext_options,TEXT("-?"))) { MessageBoxA(g_Globals._hwndDesktop, "/e open cabinet window in explorer mode\r\n" "/root open cabinet window in rooted mode\r\n" "/mdi open cabinet window in MDI mode\r\n" "/sdi open cabinet window in SDI mode\r\n" "\r\n" "-? display command line options\r\n" "\r\n" "-desktop start in desktop mode regardless of an already running shell\r\n" "-nodesktop disable desktop mode\r\n" "-explorer display cabinet window regardless of enabled desktop mode\r\n" "\r\n" "-install replace previous shell application with ROS Explorer\r\n" "\r\n" "-noautostart disable autostarts\r\n" "-autostart enable autostarts regardless of debug build\r\n" "\r\n" "-console open debug console\r\n" "\r\n" "-debug activate GDB remote debugging stub\r\n" "-break activate debugger breakpoint\r\n", "ROS Explorer - command line options", MB_OK); } Thread* pSSOThread = NULL; if (startup_desktop) { // launch SSO thread to allow message processing independent from the explorer main thread pSSOThread = new SSOThread; pSSOThread->Start(); } /**TODO launching autostart programs can be moved into a background thread. */ if (autostart) { const char* argv[] = {"", "s"}; // call startup routine in SESSION_START mode startup(2, argv); } #ifndef ROSSHELL if (g_Globals._hwndDesktop) g_Globals._desktop_mode = true; #endif int ret = explorer_main(hInstance, lpCmdLine, nShowCmd); // write configuration file g_Globals.write_persistent(); if (pSSOThread) { pSSOThread->Stop(); delete pSSOThread; } if (!any_desktop_running) { // shutdown the shell DDE server if (g_SHDOCVW_ShellDDEInit) (*g_SHDOCVW_ShellDDEInit)(FALSE); } return ret; }