我是靠谱客的博主 热情煎蛋,最近开发中收集的这篇文章主要介绍Using fork() in C/C++ to create a child process(用C创建子进程),觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, parent.
The following code briefly explains how the fork() process executes, how child treats the fork() process and how the parent treats it.
下面的代码可以通过fork来创建一个子进程,安全软件关闭应用的时候一般不会去关闭子进程,所以可以用子进程来做一些监听。
#include
#include
#include <sys/types.h>
using namespace std;
void ChildProcess(pid_t); /* child process prototype */
void ParentProcess(pid_t); /* parent process prototype */
int main(void)
{
cout<<"Before Fork: "<< getpid()<<endl;
pid_t pid; //stores the process ID
pid = fork(); //creates a child process of same program
if (pid == 0)
ChildProcess(pid); //If a child is executing a process,for it , PID will be 0
else
ParentProcess(pid); //The parent can have access to child process PID
return 0;
}
void ChildProcess(pid_t pid)
{
cout<<"I am the child: "<<getpid()<<endl;
}
void ParentProcess(pid_t pid)
{
cout<<"I am the father : "<<getpid()<<" of child: "<<pid<<endl;
}
In unix, every process executed has it’s own unique Process ID(PID). When the parent created a new child by using fork(), the child gets a new unique process ID. To store this new unique process ID of child , we are using “pid” variable. The interesting part in here is that pid variable value is accessible to the parent only i.e. for the parent, the pid variable will have some unique value ( >0 ) but for the child, it’s own process ID will not be accessible and so to the child, pid appears to be 0 only.
最后
以上就是热情煎蛋为你收集整理的Using fork() in C/C++ to create a child process(用C创建子进程)的全部内容,希望文章能够帮你解决Using fork() in C/C++ to create a child process(用C创建子进程)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复