基于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;
}
相关推荐
阿里云大数据AI技术13 小时前
阿里云 EMR AI 助手正式发布:从问答工具到全栈智能运维助手
运维·人工智能
你好潘先生19 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
orion571 天前
Missing Semester Class1:course overview and introduction of shell
linux
SkyWalking中文站1 天前
认识 Horizon UI · 6/17:Trace 探索器
运维·监控·自动化运维
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式
程序员老赵2 天前
服务器文件不想 SFTP 上传?Docker 跑个 File Browser,浏览器就能管理
服务器·docker·开源
火车叼位2 天前
写给初级开发者:SSL、SSH、HTTPS 与证书体系全解析
运维
vivo互联网技术2 天前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
用户805533698032 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式