linux下利用fork()函數創建進程

#include
#include<unistd.h>
#include<cstdlib>
void forklt(const pid_t &it)
{
    if(it < 0)
    {
        std::cout<<"fork error"<<std::endl;
        exit(1);
    }
}
int main()
{
    char *s;
    pid_t pid;
    pid = fork();
    forklt(pid);
    if(pid == 0)
    {
        pid_t pida;
        pida = fork();
        forklt(pida);
        if(pida == 0)
        {
            while(1)
                        {
                            std::cout<<"this is a A_1_1 :"<<getpid()<<" :"<<getppid()<<std::endl;
                            sleep(3);
                    }

        }
        else
        {
            pid_t pidt;
            pidt = fork();
            forklt(pidt);
            if(pidt == 0)
            {
                while(1)
                {
                    std::cout<<"this is a A_1_2 :"<<getpid()<<" :"<<getppid()<<std::endl;
                    sleep(3);
                }
                
            }
            else
            {
                while(1)
                           {
                                   std::cout<<"this is a A_1 :"<<getpid()<<" :"<<getppid()<<std::endl;
                                sleep(3);
                        }
            }    
        }
    }
    else
    {
        pid_t pidA;
        pidA = fork();
        forklt(pidA);
        if(pidA == 0)
        {
            
            while(1)
                    {
                            std::cout<<"this is a A_2 :"<<getpid()<<" :"<<getppid()<<std::endl;
                            sleep(3);
                    }
        }
        else
        {
            while(1)
            {
                std::cout<<"this is a A :"<<getpid()<<" :"<<getppid()<<std::endl;
                sleep(3);
            }
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章