Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // HW2.cpp : Defines the entry point for the console application.
- //
- #include <stdio.h>
- #include <iostream>
- #include <unistd.h>
- #include <sys/types.h>
- #include <fstream>
- using namespace std;
- int main(int argc, char* argv[])
- {
- pid_t pid;
- pid_t mainPid;
- pid_t firstChild;
- pid_t secondChild;
- pid_t thirdChild;
- mainPid = getpid();
- // Fork 3 child processes
- pid = fork();
- firstChild = getpid();
- if (mainPid == getpid())
- {
- pid = fork();
- secondChild = getpid();
- }
- if (mainPid == getpid())
- {
- pid = fork();
- thirdChild = getpid();
- }
- // Parent process displays PID
- if (pid > 0)
- {
- cout << "This is the main process, my PID is " << getpid() << endl;
- }
- // One child process run "ls -l" command (using "execl" system call)
- if (pid == 0 && firstChild == getpid())
- {
- execl("/bin/ls", "ls", "-l", 0);
- }
- // Another child process run the "ps -ef"
- if (pid == 0 && secondChild == getpid())
- {
- execl("/bin/ps", "ps", "-ef", 0);
- }
- // The 3rd child process displays the content of the file. (use "more" or "cat")
- if (pid == 0 && thirdChild == getpid())
- {
- ///////// This code section will open a local text file and display its contents////
- fstream fIn;
- fIn.open(argv[1], ios::in);
- if (fIn.is_open())
- {
- string s;
- while (getline(fIn, s))
- {
- cout << s << endl;
- }
- fIn.close();
- }
- else
- cout << "Error opening file " << endl;
- ///////////////////////////////////////
- }
- //After all child processes terminate, the main process displays "main process terminates" then exits
- if (pid > 0)
- {
- wait(NULL);
- wait(NULL);
- wait(NULL);
- cout << "main process terminates" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement