• 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);
    }

  • 相关阅读:
    antd表单验证图片 必须上传
    interface和type的区别
    Typescript+React封装路由拦截组件
    redux和sessionStorage,localStorage的区别
    ES6中数组和对象的扩展运算符拷贝问题以及常用的深浅拷贝方法
    从变量提升角度看待暂时性死区
    MySQL修改root密码
    用VScode配置Python开发环境
    element UI 制作带月份快捷选项的时间选择器
    React v16.4 的生命周期
  • 原文地址:https://www.cnblogs.com/wuyuxin/p/7019926.html
Copyright © 2020-2023  润新知