zoukankan      html  css  js  c++  java
  • fork函数 linux创建子进程

    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <cstdlib>
    int a = 1;
    int main() {
        pid_t pid;
        const char *msg;
        int k;
        printf("Process Creation Study
    ");
        pid = fork();
        if(pid) printf("parent a:%d
    ",a);
        else printf("child a:%d
    ",a);
        switch(pid) {
            case 0:
                msg = "Child process is running";
                k = 3;
                a = 2;
                break;
            case -1:
                perror("Process creation failed
    ");
                break;
            default:
                msg = "Parent process is running";
                k = 5;
                a = 3;
                break;
        }
        if(pid) printf("parent a:%d
    ",a);
        else printf("child a:%d
    ",a);
        while(k > 0) {
            puts(msg);
            sleep(1);
            k--;
            printf("aa:%d
    ",a);
        }
    
        exit(0);
    }

    运行结果:

    Process Creation Study
    parent a:1
    parent a:3
    Parent process is running
    child a:1
    child a:2
    Child process is running
    aa:2
    aa:3
    Child process is running
    Parent process is running
    aa:2
    aa:3
    Child process is running
    Parent process is running
    aa:3
    Parent process is running
    aa:2
    aa:3
    Parent process is running
    aa:3

    以上可知父进程和子进程的全局变量和局部变量是不共享的,一方改变变量不会影响另一方执行

  • 相关阅读:
    归并排序
    数据组合求值
    轨道周期
    类及对象构建
    日期改写
    排列组合去重
    库存更新
    Java性能测试从入门到放弃-详解篇
    Java性能测试从入门到放弃-概述篇
    cocos2d-x安装教程
  • 原文地址:https://www.cnblogs.com/cdyboke/p/7856867.html
Copyright © 2011-2022 走看看