UNIX环境高级编程1.6 程序和进程

fork的子进程的代码只能从被创建开始

#include <ntsid.h>
#include <unistd.h>
#include <printf.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    pid_t pid;

    int loop;
    //获得当前进程ID
    printf("Current Process Id = %d \n", getpid());

    for (loop = 0; loop < 2; loop++) {

        //fork创建子进程
        if ((pid = fork()) < 0) {
            printf("退出程序\n");
            exit(1);

        } else if (pid == 0) {

            //创建子进程后,子进程返回0,通过getPid得到当前进程,getPPid得到父进程
            printf("Child Process  loop = %d,  Current Pid = %d , Parent Pid = %d\n", loop, getpid(), getppid());

        } else {
            //创建子进程后,pid就是子进程ID
            printf("Child Process  loop = %d, Current Pid = %d,childPid = %d\n", loop, getpid(), pid);
            sleep(5);
        }
    }
    return 0;
}

执行结果:

Current Process Id = 813 
Child Process  loop = 0, Current Pid = 813,childPid = 819
Child Process  loop = 0,  Current Pid = 819 , Parent Pid = 813
Child Process  loop = 1, Current Pid = 819,childPid = 820
Child Process  loop = 1,  Current Pid = 820 , Parent Pid = 819
Child Process  loop = 1, Current Pid = 813,childPid = 821
Child Process  loop = 1,  Current Pid = 821 , Parent Pid = 813
Program ended with exit code: 0

fork后面的程序都会被子程序执行

#include <ntsid.h>
#include <unistd.h>
#include <printf.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    pid_t pid;

    int loop;
    //获得当前进程ID
    printf("Current Process Id = %d \n", getpid());

    for (loop = 0; loop < 2; loop++) {

        //fork创建子进程
        if ((pid = fork()) < 0) {
            printf("退出程序\n");
            exit(1);

        } else if (pid == 0) {

            //创建子进程后,子进程返回0,通过getPid得到当前进程,getPPid得到父进程
            printf("Child Process  loop = %d,  Current Pid = %d , Parent Pid = %d\n", loop, getpid(), getppid());

        } else {
            //创建子进程后,pid就是子进程ID
            printf("Child Process  loop = %d, Current Pid = %d,childPid = %d\n", loop, getpid(), pid);
            sleep(5);
        }
    printf("current pid is %d\n",getpid());
    }
    return 0;
}
Current Process Id = 889 
Child Process  loop = 0, Current Pid = 889,childPid = 891
Child Process  loop = 0,  Current Pid = 891 , Parent Pid = 889
current pid is 891
Child Process  loop = 1, Current Pid = 891,childPid = 892
Child Process  loop = 1,  Current Pid = 892 , Parent Pid = 891
current pid is 892
current pid is 891
current pid is 889
Child Process  loop = 1, Current Pid = 889,childPid = 893
Child Process  loop = 1,  Current Pid = 893 , Parent Pid = 889
current pid is 893
current pid is 889
Program ended with exit code: 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值