zoukankan      html  css  js  c++  java
  • 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);
    }

  • 相关阅读:
    c#队列的实现
    c#队列的实现
    C# 自定义控件制作和使用实例(winform)
    常见的位运算
    Clock()函数简单使用(C库函数)
    Python全局变量的简单使用
    PyQt5+Caffe+Opencv搭建人脸识别登录界面
    python3+pyqt5+opencv3简单使用
    OpenCV实现人脸检测
    opencv 截图并保存
  • 原文地址:https://www.cnblogs.com/jasmine-Jobs/p/4425188.html
Copyright © 2011-2022 走看看