在CentOS系统中,C++多进程编程可以通过fork()系统调用实现
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
pid_t pid = fork();
if (pid == -1) {
// fork失败
std::cerr << "Error: fork failed" << std::endl;
return 1;
} else if (pid == 0) {
// 子进程
std::cout << "I am the child process, my PID is: " << getpid() << std::endl;
// 子进程执行的代码
} else {
// 父进程
std::cout << "I am the parent process, my PID is: " << getpid() << ", and my child's PID is: " << pid << std::endl;
// 父进程执行的代码
}
int status;
pid_t result = waitpid(pid, &status, 0);
if (result == -1) {
std::cerr << "Error: waitpid failed" << std::endl;
return 1;
}
这是一个简单的C++多进程编程示例。在实际应用中,您可能需要根据需求对代码进行调整。注意,多进程编程可能会遇到一些问题,例如僵尸进程、竞态条件等,因此在编写代码时要特别注意这些问题。