sistema_progs

Programas para customizar o meu entorno de traballo nos meus equipos persoais
Log | Files | Refs

D1273.test1.c (1469B)


      1 // This is MinGW Program
      2 
      3 #include <stdio.h>
      4 #include <windows.h>
      5 #include <sys/stat.h>
      6 
      7 BOOL is_process_alive(HANDLE handle) {
      8   DWORD result;
      9   return GetExitCodeProcess(handle, &result) && result == STILL_ACTIVE;
     10 }
     11 BOOL is_file(const char* filename) {
     12   struct stat st;
     13   if (stat(filename, &st) == 0 && S_ISREG(st.st_mode)) return TRUE;
     14   return FALSE;
     15 }
     16 
     17 int main(int argc, char** argv) {
     18   const char* winpid = argv[1];
     19   const char* filename = argv[2];
     20 
     21   int ppid = atoi(winpid);
     22   if (!ppid) {
     23     fprintf(stderr, "invalid process ID '%s'\n", winpid);
     24     return 1;
     25   }
     26   HANDLE parent_process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ppid);
     27   if (parent_process == NULL) {
     28     fprintf(stderr, "failed to open the parent process '%s'\n", winpid);
     29     return 1;
     30   }
     31 
     32   int exit_code = 0;
     33   BOOL terminate = FALSE;
     34   while (!terminate) {
     35     FILE* f = fopen(filename, "r");
     36     if (!f) {
     37       fprintf(stderr, "failed to open the file '%s'\n", filename);
     38       terminate = TRUE;
     39       exit_code = 1;
     40       break;
     41     }
     42     unlink(filename);
     43     for (;;) {
     44       if (!is_process_alive(parent_process)) {
     45         terminate = TRUE;
     46         break;
     47       }
     48       if (is_file(filename)) break; // reopen
     49 
     50       int count = 0;
     51       char buff[4096];
     52       while (count = fread(&buff, 1, sizeof buff, f))
     53         fwrite(buff, 1, count, stdout);
     54       fflush(stdout);
     55       Sleep(20);
     56     }
     57     fclose(f);
     58   }
     59 
     60   CloseHandle(parent_process);
     61   return exit_code;
     62 }