Linux:创建子进程并获取子进程id和父进程id;getpid() getppid()

1.touch myprocess.c
2.ls > Makefile
3.vim Makefile
在这里插入图片描述

 myprocess:myprocess.c
   gcc -o myprocess myprocess.c 
 .PHONY:clean 
 clean:
   rm -f myprocess 

4.创建子进程 make fork
在这里插入图片描述
6.查看fork手册 man fork(如果创建成功,返回子进程id ,父进程0;如果创建失败,返回-1)
在这里插入图片描述

5.vim myprocess.c 并且创建子进程
在这里插入图片描述

 #include<stdio.h>
 #include<unistd.h>
 
 int main()
{
    
    
   pid_t id = fork();                                                                                                                             
                                                                                                                                               
   return 0;                                                                                                                                   
 }                                                                                                                                             
~           
  1. 获取子进程id和父进程id;getpid() getppid()
   #include<stdio.h>  
   #include<unistd.h>  
     
   int main()  
   {
    
      
 pid_t id = fork();

    if(id < 0) 
    {
    
    
        perror("fork");
        return 1;
    }
    else if(id == 0)
    {
    
    
        //child
        while(1)
        {
    
    
            printf("我是子进程,pid: %d, ppid: %d\n", getpid(), getppid());
            sleep(1);
        }
    }
    else
    {
    
    
        //parent
        while(2)
        {
    
    
            printf("我是父进程, pid: %d, ppid: %d\n", getpid(), getppid());
            sleep(3);
        }
    }                                                                                                                                
   return 0;                                                      
 }    

7.make一下,生成myprocess运行文件,然后./myprocess
ppid:9101是bash,也就是命令行解释器
在这里插入图片描述
8.清除myprocess运行文件: make clean
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47952981/article/details/129597833