1、fork函数用于创建子进程,其特殊性在于调用一次fork函数,会得到两次返回值:
1)在父进程中,fork返回新创建子进程的进程ID;
2)在子进程中,fork返回0;
3)如果出现错误,fork返回一个负值;
简单示例:
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
pid_t pid;
cout << "begin process..." << endl;
pid = fork();
if (pid == -1)
{
cout << "fork error." << endl;
exit(1);
}
else if (pid == 0)
{
cout << "Im a child,pid = " << getpid() << ",ppid = " << getppid() << endl;
}
else
{
cout << "Im a parent,pid = " << getpid() << ",ppid = " << getppid() << endl;
//延时,保证父进程后退出
sleep(1);
}
cout << "end process..." << endl;
}
运行结果:
2、简单示例,创建5个子进程:
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int i;
pid_t pid;
cout << "begin process..." << endl;
for (i = 0; i < 5; ++i)
{
pid = fork();
if (pid == 0) //子进程
{
break;
}
}
sleep(i);
if (i < 5)
{
cout << "我是第 " << i + 1 << " 个子进程,pid = " << getpid() << endl;
}
else
{
cout << "我是父进程" << endl;
}
cout << "end process..." << endl;
return 0;
}
3、父子进程共享机制:读时共享,写时复制。
4、fork函数的作用,来自别处作为参考:
当你要创建一个子进程的时候就用fork()函数,它一般有两种应用,
第一,创建一个子进程用来执行和父进程不同的代码段,这个在网络中应用比较广,比如服务器端fork一个子进程用来等待客户端的请求,当请求到来时,子进程响应这个请求,而父进程则继续等待客户端请求的到来;
第二,创建一个子进程用来执行和父进程不同的程序,这种应用往往 fork一个子进程之后立即调用exec族函数,exec族函数则调用新的程序来代替新创建的子进程。
5、让子进程调用一个程序执行其它操作:
此处使用exec函数族中的函数:execlp和execl,函数只在执行错误的时候返回。
execlp:在环境变量所指的目录中查找参数file所指的文件(可执行程序);
execl:在path字符串所指的目录中查找可执行程序;
int execl(const char *path, const char *arg, ...
/* (char *) NULL */);
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
简单示例:
#include "stdlib.h"
#include "unistd.h"
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
pid_t pid;
pid = fork();
if (pid == -1)
{
cout << "fork error." << endl;
exit(1);
}
else if (pid == 0)
{
cout << "Im a child,pid = " << getpid() << ",ppid = " << getppid() << endl;
//调用一个新进程来代替子进程
execlp("ls", "ls", "-l", NULL);
//如果执行失败,才能执行到此处:结束子进程
exit(0);
}
else
{
cout << "Im a parent,pid = " << getpid() << ",ppid = " << getppid() << endl;
//延时,保证父进程后退出
sleep(1);
}
return 0;
}