您的位置:首页 > 编程语言 > C语言/C++

Using fork() in C/C++ to create a child process(用C创建子进程)

2014-04-30 18:23 597 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: