linux fork 多进程创建

1)fork函数将运行着的程序分成2个(几乎)完全一样的进程,每个进程都启动一个从代码的同一位置开始执行的线程。
这两个进程中的线程继续执行,就像是两个用户同时启动了该应用程序的两个副本。
2)fork函数被调用一次但返回两次。两次返回的唯一区别是子进程中返回0值而父进程中返回子进程ID。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>

#define LOOP_NUM 5 //create process number

int main()
{

    int idx=0;
    pid_t childpid=0;
    char cmd[16]={0,};

    printf("LOOP start:--> \n");
    while (1)
    {
        if(idx>=LOOP_NUM)
        {
        	break;
        }
        idx++;

        printf(" create pid=%d ppid=%d idx=%d \n", getpid(), getppid(), idx);
        childpid = fork();

        if (childpid == 0)
        {
            // 子进程中
            printf("  C runing 1 pid=%d ppid=%d idx=%d \n", getpid(), getppid(), idx);
            sleep(1);
            printf("  C runing 2 pid=%d ppid=%d idx=%d \n", getpid(), getppid(), idx);
            //
            break;
        }
        else if (childpid > 0)
        {
            // 父进程中
        }
        else
        {
            //错误
            printf("fork error pid=%d idx=%d \n", getpid(), idx);
            wait(NULL);
        }
    }

    //父进程中回收资源
    if(childpid > 0)
    {
        //childpid is child process pid in the parent process
        printf("FIRST PROCESS:parent create process finished! waiting for children pid=%d childpid=%d \n", getpid(), childpid);
        sprintf(cmd,"ps -ef | grep %d",getpid());
        system(cmd);
        //printf("\n\n %s \n\n", cmd);
        wait(NULL);
        printf("FIRST PROCESS: all exit & wait over pid=%d \n", getpid());
    }
    else
    {
        printf("  <--pid=%d  ppid=%d childpid=%d idx=%d will exit \n", getpid(), getppid(), childpid, idx);
    }
    //exit(0);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/poject/article/details/85456329