pid_t pid = fork(); switch (pid) { case -1: cerr << "Fork is failed!\n"; break; case 0: cout << "This is child process, pid: " << getpid(); cout << ", parent pid: " << getppid() << endl; break; default: cout << "This is parent process, pid: " << getpid(); cout<< ", child pid: " << pid << endl; }
fork()
函数创建的子进程会完全复制父进程的资源,代码也不例外,但是fork()
函数在父进程中返回的是子进程的pid
,如果为-1
则说明创建子进程失败;在子进程中返回的是0
,可以借此区分父进程和子进程。