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\n");
    pid = fork();
    if(pid) printf("parent a:%d\n",a);
    else printf("child a:%d\n",a);
    switch(pid) {
        case 0:
            msg = "Child process is running";
            k = 3;
            a = 2;
            break;
        case -1:
            perror("Process creation failed\n");
            break;
        default:
            msg = "Parent process is running";
            k = 5;
            a = 3;
            break;
    }
    if(pid) printf("parent a:%d\n",a);
    else printf("child a:%d\n",a);
    while(k > 0) {
        puts(msg);
        sleep(1);
        k--;
        printf("aa:%d\n",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

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

posted @ 2017-11-18 15:42  cdongyang  阅读(610)  评论(0编辑  收藏  举报