4

Launch a child process and kill it

  1. /*
  2.  * Forks and kills child.
  3.  *
  4.  *   fork
  5.  *   kill
  6.  *   wait
  7.  *   WIFEXITED
  8.  *   WEXITSTATUS
  9.  *   WTERMSIG
  10.  *   getpid
  11.  *   sleep
  12.  */
  13.  
  14. #include <sys/types.h>
  15. #include <sys/wait.h>
  16. #include <signal.h>
  17. #include <unistd.h>
  18.  
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <errno.h>
  22. #if defined( LINUX )
  23. #include <string.h>
  24. #endif
  25.  
  26. #define SLEEPTIME               2               /* in secs */
  27.  
  28. int main(int argc, char *argv[]) {
  29.     int pid, status, died;
  30.     int killer = 0;
  31.  
  32.     switch (argc) {
  33.     case 2:
  34.         if (strcmp(argv[1], "-k") != 0)
  35.             goto usage;
  36.         killer = 1;
  37.         break;
  38.     case 1:
  39.         break;
  40.     default:
  41.         usage: fprintf(stderr, "%s [-k]\n", argv[0]);
  42.         exit(1);
  43.     }
  44.  
  45.     fprintf(stdout, "%i running...\n", getpid());
  46.  
  47.     pid = fork();
  48.  
  49.     if (pid == -1) { /* error */
  50.         fprintf(stderr, "%s\n", strerror(errno));
  51.         exit(1);
  52.     }
  53.  
  54.     if (pid == 0) { /* child */
  55.         fprintf(stdout, "%i sleeping for %i secs...\n", getpid(), SLEEPTIME);
  56.         sleep(SLEEPTIME);
  57.         /* exit with an error half the time */
  58.         exit(getppid() & 1);
  59.     }
  60.  
  61.     /* kill child? */
  62.     if (killer) {
  63.         fprintf(stdout, "%i killing %i...\n", getpid(), pid);
  64.         kill(pid, SIGKILL);
  65.     }
  66.  
  67.     /* wait for child */
  68.     fprintf(stdout, "%i waiting for %i...\n", getpid(), pid);
  69.     died = wait(&status);
  70.     if (WIFEXITED(status))
  71.         fprintf(stdout, "%i exited with status %i\n", died, WEXITSTATUS(status));
  72.     else
  73.         fprintf(stdout, "%i killed with signal %i\n", died, WTERMSIG(status));
  74.     fprintf(stdout, "%i bye\n", getpid());
  75.  
  76.     exit(0);
  77. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].