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来创建一个子进程,安全软件关闭应用的时候一般不会去关闭子进程,所以可以用子进程来做一些监听。
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.
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.
相关文章推荐
- C++ 的template
- jni 调用c和c++的区别.
- C++ 11
- 组合模式及C++代码实现
- C语言之关键字(一)
- C语言编写的bmp读写程序
- 高性能并发队列(C++实现)
- 游戏中C++调用Java
- <c语言深度解剖>第二章符号笔记
- C/C++日常学习总结(第八篇)winsock建立连接的步骤&窗口的生成
- 30分钟了解C++11新特性
- 孙鑫VC++深入详解(8):定制应用程序外观
- C++程序一闪就关闭的问题解决
- C++术语
- 【C语言】13-指针和字符串
- C语言实现通用链表初步(二)
- c/c++中内存区域划分大总结
- C++中引用(&)的用法和应用实例
- C语言实现通用链表初步(二)
- C++的前置声明详解