Linux进程相关函数(—)

目录

创建子进程

获取进程PID

DEMO1-基本函数使用

DEMO2-循环创建子进程


创建子进程

—fork函数

            pid_t fork(void);

            成功返回两次,在父进程中返回子进程pid,子进程中返回 0,失败返回  -1 并设置 errno  

获取进程PID

—getpid函数

             pid_t getpid(void); —— 获取当前进程PID
             pid_t getppid(void); —— 获取父进程PID

            返回 pid

DEMO1-基本函数使用

使用fork函数创建子进程,getpid获取进程pid,getppid获取父进程pid。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
        pid_t pid;

        printf("The program is executing!\n");  //the current program execued informations

        printf("===============================================\n");

        pid = fork();
        if(pid == -1){

                perror("fork error");   //the child process failed to creat
                exit(0);
        }else if(pid > 0){

                printf("This is father process:\n");    //father process
                printf("return pid is child pid in father process = %d\n",pid); //child process pid
                printf("father process pid = %d\n",getpid());   //getpid get current process pid
                sleep(1);
        }else if(pid == 0){

                printf("===============================================\n");
                printf("this is child process:\n");     //child process
                printf("the child process pid = %d\n",getpid());        //child process pid
                printf("my father process pid = %d\n",getppid());//getppid get chird of father pocess pid
                printf("===============================================\n");
        }

        printf("process end!\n");       //

        return 0;
}

DEMO2-循环创建子进程

使用fork函数循环创建多个子进程,并且被创建的子进程打印自己是第几个被创建的以及自己pid。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

#define CREATFORKNUM 10

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

        pid_t pid[CREATFORKNUM] = {0};
        int i;
        for(i=0;i < CREATFORKNUM; i++){

                pid[i] = fork();        //creat child process
                if(pid[i] == 0){
                        break;
                }
                sleep(1);       //sequential execution
        }
        if(i == 10){
                exit(0);        //because 0-10 = 11,therefore i=10 exit
        }else
                printf("This is %dth created || my pid = %d\n",i+1,getpid());   //

        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值