Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab3/ex2_vfork.cpp
221 views
1
#include <iostream>
2
#include <string>
3
#include <sys/types.h>
4
#include <unistd.h>
5
#include <stdlib.h>
6
7
using namespace std;
8
int globalVariable = 2;
9
10
int main()
11
{
12
string sIdentifier;
13
int iStackVariable = 20;
14
pid_t pID = vfork();
15
if (pID == 0) // child
16
{
17
// Code only executed by child process
18
sIdentifier = "Child Process: ";
19
globalVariable++;
20
iStackVariable++;
21
cout << sIdentifier;
22
cout << " Global variable: " << globalVariable;
23
cout << " Stack variable: " << iStackVariable << endl;
24
exit(0);
25
}
26
else if (pID < 0) // failed to fork
27
{
28
cerr << "Failed to fork" << endl;
29
exit(1);
30
// Throw exception
31
}
32
else // parent
33
{
34
// Code only executed by parent process
35
sIdentifier = "Parent Process:";
36
}
37
// executed only by parent
38
cout << sIdentifier;
39
cout << " Global variable: " << globalVariable;
40
cout << " Stack variable: " << iStackVariable << endl;
41
exit(0);
42
}
43
44