code_junkie

How do I write a program that tells when my other program ends?

Nov 11th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. #include <sys/ptrace.h>
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <signal.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7.  
  8. int main(int argc, char** argv) {
  9.  
  10. int pid = atoi(argv[1]);
  11. int status;
  12. siginfo_t si;
  13.  
  14. switch (ptrace(PTRACE_ATTACH, pid, NULL)) {
  15. case 0:
  16. break;
  17. case -ESRCH:
  18. case -EPERM:
  19. return 0;
  20. default:
  21. fprintf(stderr, "Failed to attach childn");
  22. return 1;
  23. }
  24. if (pid != wait(&status)) {
  25. fprintf(stderr, "wrong wait signaln");
  26. return 1;
  27. }
  28. if (!WIFSTOPPED(status) || (WSTOPSIG(status) != SIGSTOP)) {
  29. /* The pid might not be running */
  30. if (!kill(pid, 0)) {
  31. fprintf(stderr, "SIGSTOP didn't stop childn");
  32. return 1;
  33. } else {
  34. return 0;
  35. }
  36. }
  37. if (ptrace(PTRACE_CONT, pid, 0, 0)) {
  38. fprintf(stderr, "Failed to restart childn");
  39. return 1;
  40. }
  41.  
  42. while (1) {
  43. if (waitid(P_PID, pid, &si, WSTOPPED | WEXITED)) {
  44. // an error occurred.
  45. if (errno == ECHILD)
  46. return 0;
  47. return 1;
  48. }
  49. errno = 0;
  50.  
  51. if (si.si_code & (CLD_STOPPED | CLD_TRAPPED)) {
  52. /* If the child gets stopped, we have to PTRACE_CONT it
  53. * this will happen when the child has a child that exits.
  54. **/
  55. if (ptrace(PTRACE_CONT, pid, 1, si.si_status)) {
  56. if (errno == ENOSYS) {
  57. /* Wow, we're stuffed. Stop and return */
  58. return 0;
  59. }
  60. }
  61. continue;
  62. }
  63.  
  64. if (si.si_code & (CLD_EXITED | CLD_KILLED | CLD_DUMPED)) {
  65. return si.si_status;
  66. }
  67. // Fall through to exiting.
  68. return 1;
  69. }
  70. }
  71.  
  72. use POSIX qw(:sys_wait_h);
  73.  
  74. sub child_handler {
  75.  
  76. while ((my $child = waitpid(-1, WNOHANG)) > 0) {
  77. # We've caught a process dying, its PID is now in $child.
  78. # The exit value and other information is in $?
  79. }
  80.  
  81. $SIG{CHLD} &child_handler; # SysV systems clear handlers when called,
  82. # so we need to re-instate it.
  83. }
  84.  
  85. # This establishes our handler.
  86. $SIG{CHLD} = &child_handler;
  87.  
  88. bool WaitForProcessExit( DWORD _dwPID )
  89. {
  90. HANDLE hProc = NULL;
  91. bool bReturn = false;
  92.  
  93. hProc = OpenProcess(SYNCHRONIZE, FALSE, _dwPID);
  94.  
  95. if(hProc != NULL)
  96. {
  97. if ( WAIT_OBJECT_0 == WaitForSingleObject(hProc, INFINITE) )
  98. {
  99. bReturn = true;
  100. }
  101. }
  102.  
  103. CloseHandle(hProc) ;
  104. }
  105.  
  106. return bReturn;
  107. }
  108.  
  109. Foo {
  110. func Stops(foo_sub) { run foo_sub; return 1; }
  111. }
Add Comment
Please, Sign In to add comment