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

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

原文地址:https://www.cnblogs.com/cdyboke/p/7856867.html