基于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;
}
相关推荐
leisoo80972 小时前
100GBA股股票数据怎么存ClickHouseRedisMySQLJSON完整对比
大数据·linux·服务器·开发语言·python
爱喝水的鱼丶3 小时前
SAP-ABAP:接口与报表场景专项优化:RFC/ODATA 接口、ALV 报表的性能提升方案
运维·性能优化·接口·sap·abap·rfc·经验交流
青瓦梦滋3 小时前
传输层UDP/TCP协议
linux·网络·c++·网络协议·tcp/ip·udp
ltl3 小时前
机密计算:SGX、SEV-SNP、TDX 与 ARM CCA
linux
ltl3 小时前
互联与网络:NVLink、InfiniBand、RoCE 与国产替代
linux
码上上班3 小时前
tengine知识点
linux·服务器·centos
画中有画3 小时前
自动化脚本开发最佳实践
运维·自动化
雾时之林6 小时前
Linux--软件管理、源码包安装
linux·服务器·数据库
江南风月6 小时前
如何使用WGCLOUD实现智能运维
运维·zabbix·运维开发·prometheus
xiaoxiangsiyan6 小时前
HCIA 网络技术基础核心模块详解
运维·网络·网络协议·tcp/ip·运维开发·网络基础