一、基本用法
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
using namespace std;
/* 多进程的基本用法 */
int main()
{
pid_t ret;
if ( (ret=fork()) < 0 )
{
fprintf(stderr,"fork fail. ErrNo[%d],ErrMsg[%d]\n",errno,strerror(errno));
}
else if ( 0==ret )
{
fprintf(stdout,"** child process run. pid:[%6d], ppid:[%6d],ret:[%6d] **\n",getpid(),getppid(),ret);
//exit(0); // 可以结束掉子进程,那么程序将不会再运行最后一行的printf,原因在于:fork之后的代码父子进程都可见都会执行,通过if可以控制父子进程进行执行不同的内容,原理在于fork不同于其他函数他返回两个值,给父进程返回的是子进程的pid,给子进程自己返回的是0,失败返回 -1,于是当在if中碰到exit自然子进程就结束了
}
else
{
fprintf(stdout,"** parent process run. pid:[%6d], ppid:[%6d],ret:[%6d] **\n",getpid(),getppid(),ret);
}
printf("========== last line. pid:[%6d], ppid:[%6d],ret:[%6d] ==========\n",getpid(),getppid(),ret);
}
二、阻塞方式回收进程防止僵尸进程产生
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
using namespace std;
/* 循环创建多个进程,并通过wait阻塞的方式回收进程 */
int main()
{
int p_num=5;
/* 使用循环创建多个进程 */
for ( int i=0; i < p_num; i++ )
{
int ret = 0;
if ( (ret = fork()) < 0 )
{
fprintf(stderr,"create child process error\n");
}
else if ( 0 == ret )
{
printf("child process [%d], pid[%4d] ppid[%4d]\n",i,getpid(),getppid());