A code structure
Two codes
1. Posix_process.h
/************************************************************************* > File name:posix_process.h > Auth Or:wangzhicheng > Mail: [email protected] > Created time:thu 07:35:34 PM WST ************* /#ifndef Posix_process_h#define posix_process_h# Include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <spawn.h> #include <sys/ wait.h> #include <errno.h> #include <iostream> #include <string>using namespace std;/* * POSIX Process class * */class posix_process {protected:pid_t mpid;posix_spawnattr_t mspawnattr;posix_spawn_file_actions_t Mfileactions;char **margv;char **menvp;string mprogram_path;public:posix_process (const string &program_path, Char **argv, char **envp); Posix_process (const string &program_path, Char **argv, Char **ENVP, posix_spawnattr_t &x, Posix_spawn_file_ actions_t &y); void run (void); void join (int &value);}; #endif
2. Posix_process.cpp
/************************************************************************* > File Name:posix_process.cpp > Au Thor:wangzhicheng > Mail: [email protected] > Created time:thu 07:50:36 PM WST *********** /#include "posix_process.h" posix_process::P osix_ PROCESS (const string &program_path, Char **argv, char **envp) {this->margv = ARGV;THIS->MENVP = Envp;this->m Program_path = Program_path;posix_spawnattr_init (&this->mspawnattr);p Osix_spawn_file_actions_init (& this->mfileactions);} Posix_process::P osix_process (const string &program_path, Char **argv, Char **ENVP, posix_spawnattr_t &x, Posix_ spawn_file_actions_t &y) {this->margv = ARGV;THIS->MENVP = Envp;this->mprogram_path = program_path;this- >mspawnattr = X;this->mfileactions = Y;posix_spawnattr_init (&this->mspawnattr);p Osix_spawn_file_ Actions_init (&this->mfileactions);} voidPosix_process::run (void) {Posix_spawn (&this->mpid, This->mprogram_path.c_str (), &this-> Mfileactions, &this->mspawnattr, THIS->MARGV, THIS->MENVP);} void Posix_process::join (int &value) {wait (&value);}
3. Schedule.cpp
/************************************************************************* > File Name:schedule.cpp > Author:wangzhicheng > Mail: [email protected] > Created time:thu 08:01:44 PM WST ******** /#include "posix_process.h" int main (int argc, Char **ARGV, char **envp) {string program_path;cin >> Program_path; Posix_process PROCESS (Program_path, argv, envp); int Value;process.run ();p rocess.join (value); return 0;}
4. Makefile
cc=g++all:$ (CC)-g-o main schedule.cpp posix_process.cpp posix_process.h
Three programs run
An easy-to-use C + + Process class