zoukankan      html  css  js  c++  java
  • c/c++ linux 进程 fork wait函数

    linux 进程 fork wait函数

    fork:创建子进程

    wait:父进程等待子进程结束,并销毁子进程,如果父进程不调用wait函数,子进程就会一直留在linux内核中,变成了僵尸进程。

    fork函数的详细说明:fork

    wait函数详细说明参考:wait

    例子1:不注释掉exit(0)的话,子进程不会执行到printf("end pid: %d ", getpid());这行。

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <wait.h>//wait function
    
    int main(){
      pid_t pid;
    
      pid = fork();
    
      if(pid == 0){
        printf("child process : %d
    ", getpid());
        //exit(0);
      }
      else{
        int status;
        pid_t waitpid;
    
        printf("parent process : childpid=%d , mypid=%d
    ",pid, getpid());
        waitpid = wait(&status);
        printf("waitpid:%d
    ", waitpid);
      }
      printf("end pid: %d
    ", getpid());
      return 0;
    }
    
    

    github源代码

    例子2:父进程和子进程之间,值是不共有的,你是你的,我是我的。

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    int main(){
      pid_t pid;
      int i = 100;
    
      pid = fork();
    
      if(pid == 0){
        printf("child process : %d
    ", getpid());
        i += 500;
      }
      else{
        printf("parent process : childpid=%d , mypid=%d
    ",pid, getpid());
        i += 1024;
      }
      printf("i=%d
    ", i);
    
      return 0;
    }
    
    

    github源代码

    例子3:线程之间,值是共有的。

    #include <stdio.h>
    #include <unistd.h>//sleep function
    #include <pthread.h>
    
    int global_val = 0;
    
    void* sub_thread(void *data){
      int* val = (int*)data;
    
      printf("sub_thread : val=%d
    ", *val);
    
      for(int i = 0; i < 10; ++i){
        global_val++;
        printf("sub_thread : i=%d, g=%d
    ", i, global_val);
        sleep(1);
      }
      return NULL;
    }
    
    int main(){
      pthread_t th;
      void* th_ret;
      int arg = 200;
      
      if(pthread_create(&th, NULL, sub_thread, (void*)&arg) != 0){
        perror("pthread_create");
        return 1;
      }
    
      for(int i = 0; i < 10; ++i){
        global_val++;
        printf("main: i=%d, g=%d
    ", i, global_val);
        sleep(1);
      }
    
      if(pthread_join(th, &th_ret) != 0){
        perror("pthread_join");
        return 1;
      }
    
      return 0;
    }
    
    

    github源代码

    编译时需要加 -pthread

    g++ -g process-5-thread.cpp -std=c++11 -pthread
    

    c/c++ 学习互助QQ群:877684253

    本人微信:xiaoshitou5854

  • 相关阅读:
    [P1034][NOIP2001]一元三次方程求解 (二分)
    考前停课集训 Day7 嘞
    [P4995]跳跳!(贪心)
    [P4994]终于结束的起点 (递推)
    考前停课集训 Day6 垒
    [BZOJ1899][ZJOI2004]Lunch 午餐 (DP)
    考前停课集训 Day5 累
    任务查询系统 【主席树】
    主席树入门
    HNOI2002 营业额统计 平衡树模板题 【splay】
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9808278.html
Copyright © 2011-2022 走看看