vfork_test.cpp

来自「Linux process and thread programming」· C++ 代码 · 共 47 行

CPP
47
字号
#include <iostream>#include <string>// Required by for routine#include <sys/types.h>#include <unistd.h>using namespace std;int globalVariable = 2;main(){    string sIdentifier;    int    iStackVariable = 20;    pid_t pID = vfork();    if (pID == 0)                // child    {          // Code only executed by child process        sIdentifier = "Child Process: ";        globalVariable++;        iStackVariable++;        cout << sIdentifier;        cout << " Global variable: " << globalVariable;        cout << " Stack variable: "  << iStackVariable << endl;         _exit(0);    }    else if (pID < 0)            // failed to fork    {        cerr << "Failed to fork" << endl;        exit(1);        // Throw exception    }    else                           // parent    {       // Code only executed by parent process        sIdentifier = "Parent Process:";    }   // executed only by parent    cout << sIdentifier;    cout << " Global variable: " << globalVariable;    cout << " Stack variable: "  << iStackVariable << endl;    int temp = getpid();    cout<<"pid:"<<temp<<endl;    exit(0);                                                                                 }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?