#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;

int main(){
	int bank_account=1000;
	cout<<"======================================="<<endl;
	cout<<"[SYSTEM] Original program booting up."<<endl;
	cout<<"[SYSTEM] My Process ID (PID) is: "<<getpid()<<endl;
	cout<<"[SYSTEM] Starting Bank Balance: $"<<bank_account<<"\n"<<endl;
	cout<<"=======================================\n"<<endl;
	cout<<"Calling fork() to clone this program right now...\n"<<endl;
	pid_t process_id=fork();
	if(process_id<0){
		cerr<<"FATAL ERROR: fork() failed!"<<endl;
		return 1;
	}
	else if(process_id==0){
		cout<<"  ->[CHILD] Hello! I am the new clone."<<endl;
		cout<<"  ->[CHILD] My PID is: "<<getpid()<<endl;
		cout<<"  ->[CHILD] I am stealing $500 from the bank account!"<<endl;
		bank_account-=500;
		cout<<"  ->[CHILD] My copy of the bank account now has: $"<<bank_account<<endl;
		sleep(2);
		cout<<"  ->[CHILD] Work complete. Terminating."<<endl;
		return 0;
	}
	else{
		cout<<"[PARENT] I am the original. I just birthed a child with PID: "<<process_id<<endl;
		cout<<"[PARENT] I am going to wait for my child to finifh..."<<endl;
		wait(NULL);
		cout<<"[PARENT] My child has terminated. I am now closing safely."<<endl;
		cout<<"[PARENT] Let's check my bank balance: $"<<bank_account<<endl;
	}
	return 0;
}
