fork download
  1. /** @file test.c
  2.  *
  3.  * A small example of daemon code. It forks off
  4.  * a child process, while the parent exits immediately.
  5.  *
  6.  * @todo Close file descriptors in the child.
  7.  */
  8.  
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <sys/types.h>
  13.  
  14.  
  15. /** Parameters to be passed to the daemon. */
  16. struct params {
  17. pid_t pid;
  18. unsigned sleeptime;
  19. };
  20.  
  21. /** Functionality of the child process.
  22.  *
  23.  * This is the main function of the daemon. Fill in the
  24.  * daemon functionality in this function.
  25.  *
  26.  * Any parameters that have to be passed to the daemon
  27.  * are collected in the params struct.
  28.  */
  29. void childfunc (struct params *params)
  30. {
  31. sleep(params->sleeptime);
  32. printf("Child has stopped.\n");
  33. }
  34.  
  35. int main (int argc, char* argv[])
  36. {
  37. struct params params;
  38.  
  39. printf("Parent started: ");
  40. params.sleeptime = 3;
  41. if ( (params.pid = fork()) < 0) {
  42. printf("fork failed: %m!\n");
  43. return 1;
  44. } else if (params.pid > 0) {
  45. printf("child forked with PID %d and will sleep for %u seconds.\n", params.pid, params.sleeptime);
  46. } else {
  47. childfunc(&params);
  48. }
  49.  
  50. return 0;
  51. }
  52.  
  53.  
  54.  
Success #stdin #stdout 0.01s 5440KB
stdin
Standard input is empty
stdout
Parent started: child forked with PID 32035 and will sleep for 3 seconds.