基于linux下的高并发服务器开发(第二章)- 2.3 进程创建

cpp 复制代码
/*
    #include <sys/types.h>
    #include <unistd.h>

    pid_t fork(void)
        函数的作用:用于创建子进程
        返回值:
            fork()的返回值会返回两次。一次是在父进程中,一次是在子进程中
            在父进程中返回创建的子进程的ID,
            在子进程中返回0
            如何区分父进程和子进程:通过fork返回值
            在父进程中返回-1,表示创建子进程失败,并且设置errno
*/
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(){

    //创建子进程
    pid_t pid = fork();

    //判断是父进程还是子进程
    if(pid > 0){
        printf("pid : %d\n",pid);
        //如果大于0,返回的是创建的子进程的进程号,当前是父进程
        printf("I am parent process,pid : %d,ppid : %d\n",getpid(),getppid());
    }else if(pid == 0){
        //当前是子进程
        printf("i am child process,pid : %d,ppid : %d\n",getpid(),getppid());
    }

    // for 循环
    for(int i = 0;i<3;i++){
        printf("i : %d , pid : %d\n",i,getpid());
        sleep(1);
    }

    return 0;
}
相关推荐
用户0328472220705 小时前
如何搭建本地yum源(上)
运维
A小辣椒1 天前
TShark:Wireshark CLI 功能
linux
A小辣椒2 天前
TShark:基础知识
linux
AlfredZhao2 天前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao2 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334662 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪3 天前
linux 拷贝文件或目录到指定的位置
linux
大树883 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠3 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质3 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务