Linuxマルチプロセスのfork()関数

2734 ワード

fork()関数は、呼び出しプロセスをコピーすることによって新しいプロセスを作成します.
書式:
#include
pid_t fork(void);
戻り値のタイプ:
呼び出しに失敗した場合、戻り値は0です.
呼び出しに成功すると、親プロセスにサブプロセスのプロセス番号を返し、サブプロセス0に返します.
つまり、親プロセスのプロセスと子プロセスのプロセスを同じファイルに書き込むには、値タイプの違いを返すことができます.
fork()関数プロシージャ:オペレーティングシステムはまずプロセス記述ブロックを作成し、親プロセスのすべてのプロセス記述子の情報を正確にコピーします.親プロセスと同じように(プロセスIDが異なる以外)、コードセグメント共有、データセグメントとスタックセグメントコピー、すべてのレジスタの値をすべて正確にコピーし、ファイル記述子は正確にコピーする可能性があります.
親プロセスと子プロセスの違いは次のとおりです.
原文:
* The child has its own unique process ID, and this PID does not match the ID of any existing process group (setpgid(2)). * The child's parent process ID is the same as the parent's process ID. * The child does not inherit its parent's memory locks (mlock(2), mlockall(2)). * Process resource utilizations (getrusage(2)) and CPU time counters (times(2)) are reset to zero in the child. * The child's set of pending signals is initially empty (sigpend‐ ing(2)). * The child does not inherit semaphore adjustments from its parent (semop(2)). * The child does not inherit record locks from its parent (fcntl(2)). * The child does not inherit timers from its parent (setitimer(2), alarm(2), timer_create(2)). * The child does not inherit outstanding asynchronous I/O operations from its parent (aio_read(3), aio_write(3)), nor does it inherit any asynchronous I/O contexts from its parent (see io_setup(2)). 大まかな翻訳:
1.子プロセスのプロセス番号が親プロセスと異なる.
2.サブプロセスの保留信号セットが空である.
3.子プロセスは親プロセスのタイマーを継承しません.
4.サブプロセスは親プロセスの非同期I/O操作と環境を継承しません.
すなわち、プロセスがforkを呼び出すと、サブプロセスが作成されます.このサブプロセスと親プロセスの違いは、彼のプロセスIDと親プロセスIDだけが異なり、他は同じです.プロセスクローン(clone)自身のように.サブプロセスが作成されると、親子プロセスはforkから実行され続け、システムのリソースを競合します.コードは次のとおりです.
#include 
#include 
#include 
#include 
#include 

int main()
{
    pid_t pid;
    pid=fork();
    switch(pid)
    {
        //fork    
    case -1:
        perror("fork error");
        exit(1);
        //    fork   
    case 0:
        printf("this is child process
"); printf("my pid is %d
", getpid()); printf("my parent pid is %d
", getppid()); break; default: printf("this is parent process
"); printf("my pid is %d
", getpid()); printf("my child process pid is %d
", pid); break; } }

実行結果:
this is parent process my pid is 3675 my child process pid is 3676 this is child process my pid is 3676 my parent pid is 1
サブプロセスの親プロセスPIDは1であることに注意してください.なぜなら、サブプロセスが実行されると、親プロセスが実行終了して終了するため、サブプロセスは自動的に親プロセスPIDを1に変更します.
この問題は、デバッグ状態またはサブプロセスが先に実行された場合に発生しません.