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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值