linux c 多进程fork基本用法及阻塞和非阻塞方式回收



一、基本用法


#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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值