This is a usage sample of how to fork a sub-process and wait the sub-process ended, and check its return code.
1. main.cpp
2. sub.cpp
main process will fork a process to execute the sub process, and wait until sub process is finished, and print the sub process's return code.
usage steps:
1. g++ main.cpp -o main
2. g++ sub.cpp -o sub
case 1: call sub
$ main sub main: entry main: fork subpid=1390 fork: entry, with process=sub sub: entry sub: exit main: waitpid return 512 main: WIFEXITED=2 main: exit
sub-process was normally launched, and exit with a return code 2
case 2: call un-existed sub-process
$ main fake-sub main: entry main: fork subpid=3161 fork: entry, with process=fake-sub fork: sub execvp failure main: waitpid return 2304 main: WIFEXITED=6 main: exit
sub-process cannot be launched, the return code is returned from main.cpp
case 3: call sub, and kill the sub-process before it finish
$ main sub main: entry main: fork subpid=4170 fork: entry, with process=sub sub: entry ...
now kill the sub-process in another terminal
$ kill -9 4170
$ main sub main: entry main: fork subpid=4170 fork: entry, with process=sub sub: entry main: waitpid return 9 main: WIFSIGNALED=9 main: exit
sub-process is terminated by a signal 9.
Appendix:
sub.cpp
$ cat sub.cpp
#include <string>
#include <iostream>
int main(int argc, char * argv[]) {
std::cout << "sub: entry" << std::endl;
system("sleep 10");
std::cout << "sub: exit" << std::endl;
if (argc > 1) {
return atoi(argv[1]);
}
return 0;
}
main.cpp
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <iostream>
int main(int argc, char * argv[]) {
const char * args[3];
args[0] = argc > 1 ? argv[1] : "sub";
args[1] = "2";
args[2] = NULL;
std::cout << "main: entry" << std::endl;
pid_t childpid = fork();
if (childpid == -1) { // error
std::cout << "main: cannot fork()" << std::endl;
}
else if (childpid == 0) {
std::cout << "fork: entry, with process=" << args[0] << std::endl;
if (execvp(args[0], (char **)args) == -1) { // child process
std::cout << "fork: sub execvp failure" << std::endl;
exit (6);
}
std::cout << "fork: never come here" << std::endl;
}
else { // parent process
std::cout << "main: fork subpid=" << childpid << std::endl;
int status;
if (childpid == waitpid(childpid, &status, 0)) {
std::cout << "main: waitpid return " << status << std::endl;
if (WIFEXITED(status)) {
std::cout << "main: WIFEXITED=" << WEXITSTATUS(status) << std::endl;
}
else if (WIFSIGNALED(status)) {
std::cout << "main: WIFSIGNALED=" << WTERMSIG(status) << std::endl;
}
else {
std::cout << "main: others" << std::endl;
}
}
else {
std::cout << "main: waitpid return failure" << std::endl;
}
}
std::cout << "main: exit" << std::endl;
return 0;
}
Thanks
本文介绍了一个使用C++实现的进程间通信案例,包括父进程通过fork创建子进程、执行子进程并等待其结束,以及检查返回码的过程。演示了正常执行、调用不存在的进程及信号终止子进程三种情况。
60万+

被折叠的 条评论
为什么被折叠?



