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. フォーク手動 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. それを作成し、myprocess 実行ファイルを生成してから、./myprocess
ppid: 9101 は bash、つまりコマンド ライン インタープリターです。
ここに画像の説明を挿入
8. myprocess 実行ファイルをクリアします: make clean
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_47952981/article/details/129597833