• fork新建进程


    #include <sys/types.h>
    #include<sys/wait.h>
    #include<unistd.h>
    #include<stdio.h>
    #include<stdlib.h>

    int main()
    {
      pid_t pid;                                  //记录fork()的返回值,用于区别父子进程
      char *Message;                              //用于记录输出信息
      int LoopVal;      //用于记录父子进程的循环次数
      int LoopVal1;      //用于循环
      int ExitCode;

      printf("the new fork starting ");
      pid=fork();                                        //新建子进程
      switch(pid)
        {
        case -1:      //建立进程错误       
         printf("creat new fork error!");
         exit(1);
        case 0:                                           //子进程
          Message = "This is in the child process";
          LoopVal = 7;
          ExitCode = 25;
          break;
        default:                                         //父进程
          Message = "This is in the parent process,waiting the child finished........";
          LoopVal = 5;
          ExitCode = 15;
          break;
        }
      for(LoopVal1=0;LoopVal1<LoopVal;LoopVal1++)
        {
          puts(Message);
          sleep(1);
        }
      if(pid!=0)         //父进程
        {
          int StateVal;
          pid_t ChildPid;
          ChildPid = wait(&StateVal);         //用StateVal记录状态信息,wait返回的是子进程退出时,子进程的进程id。
          printf("The child has finished with  the PID of %d ",ChildPid);
          if(WIFEXITED(StateVal))             //如果子进程正常结束,它就取一个非零值
       {

        //宏WEXITSTATUS(StateVal)是如果子进程正常结束,该宏函数的值为0,否则为非零值,与WIFEXITED(StateVal)刚好相反。
           printf("the child process has exit with code %d ",WEXITSTATUS(StateVal));

                //如果WIFEXITED非零,它返回子进程的退出码
          }                                              

          else
              printf("the child has terminated abnormally ");
        }                                                   //子进程非正常结束
        exit(ExitCode);
    }

  • 相关阅读:
    在虚拟机安装Oracle EF步骤
    ORACLE数据库入门级及操作杂记
    软技能-代码之外的生存指南读后感
    RabbitMQ 使用demo
    RabbitMQ 应用学习随笔
    mysql 发生死锁时,解决方法
    GBase存过--工作实战
    Oracle存储过程--工作实战
    浅谈Oracle、MySQL和Gbase的使用体验(一)
    seajs学习笔记
  • 原文地址:https://www.cnblogs.com/wuyuxin/p/7019926.html
Copyright © 2020-2023  润新知