Linux下創建進程


    在微服務架構下,會涉及到大量的模塊,我們需要對這些模塊進行批量化的管理,包括模塊的啟動、監控等工作。

方案一

#include <syslog.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <sys/stat.h>

int main()
{
    pid_t pid = 0;
    //創建一個子進程,fork()函數沒有參數。
    pid = fork();
    if (pid < 0)
    {
        std::cout << "error" << std::endl;
    }
    else if (0 != pid)
    {
         pause();
    }
    
     setsid();
     umask(0);
    // //關閉文件描述符
    int des=getdtablesize();
    int i=0;
    for(i=0;i<3;i++)
    {
        close(i);
    }
   
   
    //子進程得到的返回值是0,這段代碼在子進程中執行
    std::string strTp = "./binname";
    execl(strTp.c_str(), strTp.c_str(), "-cmd", "value", nullptr);
    return 0;
}

    該方法雖然可以正常創建進程,但創建的進程與當前進程存在父子關系,當前進程異常可能會導致子進程異常,所以這種辦法並不可取。

方案二

int main()
{
    pid_t pid = 0;
    //創建一個子進程,fork()函數沒有參數。
    pid = fork();
    if (pid < 0)
    {
        std::cout << "error" << std::endl;
    }
    else if (0 != pid)
    {
         pause();
    }
    
     setsid();
     umask(0);
    //關閉文件描述符
    int des=getdtablesize();
    int i=0;
    for(i=0;i<3;i++)
    {
        close(i);
    }
    if ((pid = fork()) < 0)
        std::cout << "error" << std::endl;
    else if (pid != 0) /* parent */
        exit(0);
   
    //子進程得到的返回值是0,這段代碼在子進程中執行
    std::string strTp = "./binname";
    execl(strTp.c_str(), strTp.c_str(), "-cmd", "value", nullptr);
    return 0;
}

該方法是在子進程中創建孫進程來作為執行模塊,然后子進程退出,孫進程會變成孤兒進程,由系統接管。

方案三

int fnProcess(void *stack)
{
    std::tuple<std::string, std::string, std::string> *pArg = static_cast<std::tuple<std::string, std::string, std::string> *>(stack);
    std::string strTp, strUuid, strServerName;
    std::tie(strTp, strUuid, strServerName) = *pArg;

    setsid();
    //子進程得到的返回值是0,這段代碼在子進程中執行
    execl(strTp.c_str(), strTp.c_str(), "-u", strUuid.c_str(), "-s", strServerName.c_str(), nullptr);

    delete pArg;

    return 1;
}

int main()
{
    void * stack;
    stack = malloc(FIBER_STACK);//為子進程申請系統堆棧
    if (!stack)
    {
        printf("The stack failed\n");
        exit(0);
    }
    std::tuple<std::string, std::string, std::string> *pArg = new std::tuple<std::string, std::string, std::string>(strTp, strUuid, strServerName);
    clone(&fnProcess, (char *)stack + FIBER_STACK, CLONE_PARENT, pArg);//創建子線程
}

該方案通過手動分配堆棧,將信息傳遞給子進程來實現精准控制。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM