Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. // HW2.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include <stdio.h>
  5. #include <iostream>
  6. #include <unistd.h>
  7. #include <sys/types.h>
  8. #include <fstream>
  9. using namespace std;
  10.  
  11. int main(int argc, char* argv[])
  12. {
  13.  
  14. pid_t pid;
  15. pid_t mainPid;
  16. pid_t firstChild;
  17. pid_t secondChild;
  18. pid_t thirdChild;
  19. mainPid = getpid();
  20.  
  21. // Fork 3 child processes
  22.  
  23. pid = fork();
  24. firstChild = getpid();
  25.  
  26. if (mainPid == getpid())
  27. {
  28. pid = fork();
  29. secondChild = getpid();
  30. }
  31.  
  32. if (mainPid == getpid())
  33. {
  34. pid = fork();
  35. thirdChild = getpid();
  36. }
  37.  
  38. // Parent process displays PID
  39. if (pid > 0)
  40. {
  41. cout << "This is the main process, my PID is " << getpid() << endl;
  42. }
  43. // One child process run "ls -l" command (using "execl" system call)
  44. if (pid == 0 && firstChild == getpid())
  45. {
  46. execl("/bin/ls", "ls", "-l", 0);
  47. }
  48. // Another child process run the "ps -ef"
  49. if (pid == 0 && secondChild == getpid())
  50. {
  51. execl("/bin/ps", "ps", "-ef", 0);
  52. }
  53. // The 3rd child process displays the content of the file. (use "more" or "cat")
  54. if (pid == 0 && thirdChild == getpid())
  55. {
  56. ///////// This code section will open a local text file and display its contents////
  57. fstream fIn;
  58. fIn.open(argv[1], ios::in);
  59.  
  60. if (fIn.is_open())
  61. {
  62. string s;
  63. while (getline(fIn, s))
  64. {
  65. cout << s << endl;
  66.  
  67. }
  68. fIn.close();
  69. }
  70. else
  71. cout << "Error opening file " << endl;
  72. ///////////////////////////////////////
  73. }
  74. //After all child processes terminate, the main process displays "main process terminates" then exits
  75. if (pid > 0)
  76. {
  77. wait(NULL);
  78. wait(NULL);
  79. wait(NULL);
  80. cout << "main process terminates" << endl;
  81. }
  82.  
  83.  
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement