4
0

child_test.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Base code taken from http://www-h.eng.cam.ac.uk/help/tpl/unix/fork.html
  2. * Fix for redhat suggested by Ptere Pramberger, peter@pramberger.at */
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <signal.h>
  8. void popen_sigchld_handler (int);
  9. int childtermd;
  10. int main(){
  11. char str[1024];
  12. int pipefd[2];
  13. pid_t pid;
  14. int status, died;
  15. if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
  16. printf ("Cannot catch SIGCHLD\n");
  17. _exit(-1);
  18. }
  19. pipe (pipefd);
  20. switch(pid=fork()){
  21. case -1:
  22. printf("can't fork\n");
  23. _exit(-1);
  24. case 0 : /* this is the code the child runs */
  25. close(1); /* close stdout */
  26. /* pipefd[1] is for writing to the pipe. We want the output
  27. * that used to go to the standard output (file descriptor 1)
  28. * to be written to the pipe. The following command does this,
  29. * creating a new file descripter 1 (the lowest available)
  30. * that writes where pipefd[1] goes. */
  31. dup (pipefd[1]); /* points pipefd at file descriptor */
  32. /* the child isn't going to read from the pipe, so
  33. * pipefd[0] can be closed */
  34. close (pipefd[0]);
  35. /* These are the commands to run, with success commented. dig and nslookup only problems */
  36. /*execl ("/bin/date","date",0);*/ /* 100% */
  37. /*execl ("/bin/cat", "cat", "/etc/hosts", 0);*/ /* 100% */
  38. /*execl ("/usr/bin/dig", "dig", "redhat.com", 0);*/ /* 69% */
  39. /*execl("/bin/sleep", "sleep", "1", 0);*/ /* 100% */
  40. execl ("/usr/bin/nslookup","nslookup","redhat.com",0); /* 90% (after 100 tests), 40% (after 10 tests) */
  41. /*execl ("/bin/ping","ping","-c","1","localhost",0);*/ /* 100% */
  42. /*execl ("/bin/ping","ping","-c","1","192.168.10.32",0);*/ /* 100% */
  43. _exit(0);
  44. default: /* this is the code the parent runs */
  45. close(0); /* close stdin */
  46. /* Set file descriptor 0 (stdin) to read from the pipe */
  47. dup (pipefd[0]);
  48. /* the parent isn't going to write to the pipe */
  49. close (pipefd[1]);
  50. /* Now read from the pipe */
  51. fgets(str, 1023, stdin);
  52. /*printf("1st line output is %s\n", str);*/
  53. /*while (!childtermd);*/ /* Uncomment this line to fix */
  54. died= wait(&status);
  55. /*printf("died=%d status=%d\n", died, status);*/
  56. if (died > 0) _exit(0);
  57. else _exit(1);
  58. }
  59. }
  60. void
  61. popen_sigchld_handler (int signo)
  62. {
  63. if (signo == SIGCHLD) {
  64. /*printf("Caught sigchld\n");*/
  65. childtermd = 1;
  66. }
  67. }