forker.cpp

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc4000/spring2026/notes/ch3/code/forker.cpp
 
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <sys/wait.h>

using namespace std;

void ReportAboutMe();

int main()  {

    ReportAboutMe();

    cout << "About to fork " << endl;

    pid_t child{fork()};
    if (child == 0) {
       cout << "A report from the child " << endl;
       ReportAboutMe();
       return 0; 
    } 

    pid_t exitProcessID{wait(nullptr)};
    cout << "Parent, child process id is " << child << endl;
    cout << "A report from the parent now that " << exitProcessID 
         << " has exited" << endl;
    ReportAboutMe();

    return 0;
}

string GetComm(pid_t pid) {
    string commFileName{"/proc/"+to_string(pid)+"/comm"};
    ifstream commFile{commFileName};

    string comm;

    getline(commFile, comm);
    commFile.close();
    return comm;
}


void ReportAboutMe() {
    pid_t myPid{getpid()};
    pid_t myParent{getppid() };

    cout << "Process id: " << myPid << endl;
    cout << "My name: " << GetComm(myPid) << endl;
    cout << "Parent process id: " << myParent << endl;
    cout << "Parent name: " << GetComm(myParent) << endl;
    cout << endl;
    return;
}