fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. #include <string.h>
  7.  
  8. void sum_of_digits()
  9. {
  10. int num, sum = 0, rem;
  11.  
  12. printf("Enter the number: ");
  13. scanf("%d", &num);
  14.  
  15. while (num != 0) {
  16. rem = num % 10;
  17. sum += rem;
  18. num /= 10;
  19. }
  20.  
  21. printf("Sum of Digits: %d\n", sum);
  22. }
  23.  
  24. int main(int argc, char *argv[])
  25. {
  26. pid_t c1, c2;
  27.  
  28. if (argc > 1 && strcmp(argv[1], "sum") == 0) {
  29. sum_of_digits();
  30. return 0;
  31. }
  32.  
  33. c1 = fork();
  34.  
  35. if (c1 == 0) {
  36. execlp("echo", "echo", "Happy new year", NULL);
  37. _exit(1);
  38. }
  39. else {
  40. wait(NULL);
  41.  
  42. c2 = fork();
  43.  
  44. if (c2 == 0) {
  45. execlp(argv[0], argv[0], "sum", NULL);
  46. _exit(1);
  47. }
  48. else {
  49. wait(NULL);
  50. printf("Parent exiting …good bye....\n");
  51. }
  52. }
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0.01s 5316KB
stdin
123
stdout
Happy new year
Enter the number: Sum of Digits: 6
Parent exiting …good bye....