如何不拷贝资源的使用fork

我们知道fork出的子进程会把父线程的资源拷贝一遍,其中包括文件描述符表,如果是一些独占的设备,那么经常会出问题。
比如你在父进程ose了设备,但子进程的文件描述符表里依然记录是open的,这样当你再次在父进程open时,就会出错报busy等正忙提示。
当在子进程里执行execl时,先把子进程的资源全部释放,然后再另起一个进程执行参数里的命令。
如下:

bool execlSystem(char* path)
{
    
    
    pid_t pid = fork();
    if (pid == -1)
    {
    
    
        cout << " fork failed ....." << endl;
    }
    else if (pid == 0)
    {
    
    
        cout << "child process ...." << path << endl;
        execl("/usr/local/bin/Capture",  "Capture", "-d", "0", "-m", "-1",  "-v", "video.raw", "-a", "audio.raw", NULL);//-d 0 -m 2 -n 50 -v video.raw -a audio.raw
        return true;
    }
    else
    {
    
    
        cout << "parent process ...." << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43466192/article/details/132099029
今日推荐