gpt4 book ai didi

c - 如何处理多线程进程的 fork 错误?

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:55 26 4
gpt4 key购买 nike

我正在处理一个多线程进程,该进程 fork 以执行另一个进程。有时,如果执行文件不存在,fork 可能会出错。由于这个进程在 fork 之前有多个线程在运行,我有几个问题:

  1. 是否将线程复制到派生进程。
  2. 使用多线程进程处理来自 fork 的错误的最佳做法是什么。例如:

    /* in a multithreaded process */


    pid = fork();

    if(pid == 0)
    {

    execlp(filename, filename, NULL);

    fprintf(stderr, "filename doesn't exist");

    /* what do i do here if there's multiple threads running
    from the fork? */

    exit(-1);
    }

最佳答案

好吧,如果可执行文件不存在,fork 不会出错。在这种情况下,exec 错误。但是,对于您的实际问题,POSIX 声明fork 创建了一个具有单个 线程的新进程,即调用 fork 。参见 here详情:

A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources.

Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.

所以你所拥有的还可以,如果有点稀疏:-)

单个线程将在子进程中运行,如果您不能执行另一个程序,记录一条消息并退出。

并且,在基本原理部分,它解释了为什么这样做:

There are two reasons why POSIX programmers call fork(). One reason is to create a new thread of control within the same program (which was originally only possible in POSIX by creating a new process); the other is to create a new process running a different program. In the latter case, the call to fork() is soon followed by a call to one of the exec functions.

The general problem with making fork() work in a multi-threaded world is what to do with all of the threads. There are two alternatives. One is to copy all of the threads into the new process. This causes the programmer or implementation to deal with threads that are suspended on system calls or that might be about to execute system calls that should not be executed in the new process. The other alternative is to copy only the thread that calls fork(). This creates the difficulty that the state of process-local resources is usually held in process memory. If a thread that is not calling fork() holds a resource, that resource is never released in the child process because the thread whose job it is to release the resource does not exist in the child process.

When a programmer is writing a multi-threaded program, the first described use of fork(), creating new threads in the same program, is provided by the pthread_create() function. The fork() function is thus used only to run new programs, and the effects of calling functions that require certain resources between the call to fork() and the call to an exec function are undefined.

关于c - 如何处理多线程进程的 fork 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com