在共享库中调用 fork

Calling fork in shared library

在将从另一个主机进程调用的共享库中使用 fork 通常是安全的?

共享库会分叉以并行执行一个过程(与线程不同,分叉进程有单独的内存空间的额外保护),然后在退出过程之前杀死分叉进程。

如果临时复制主机可执行文件,它是否有任何副作用?

还有没有办法使用 CreateProcess 将其移植到 Windows?

在 Linux 上,fork() 的规则在 fork man page. I don't believe there is a difference between calling fork() from within the core of your application and calling it from within a shared library. I.e., the child process will still be identical to the parent process except that it won't inherit the parent's memory locks, asynchronous I/O operations, etc. See man fork 中列出以获取详细信息。

这是一个提供 fork_wrapper() 函数的示例 C 程序。

==> fork_wrapper.h <==
#include <unistd.h>     // For fork(), etc.

pid_t fork_wrapper();

==> fork_wrapper.c <==
// To compile: gcc -c -fpic -o fork_wrapper.o fork_wrapper.c && gcc -shared -o libfork_wrapper.so fork_wrapper.o
#include <stdlib.h>     // For exit()
#include <stdio.h>      // For I/O
#include <string.h>     // For strerror(), memcpy(), etc.
#include <errno.h>      // For errors reported by 'nix system calls.
#include <unistd.h>     // For fork(), etc.

pid_t fork_wrapper()
{
    pid_t child = fork();
    if (-1 == child)
    {
        printf("fork_wrapper: fork(): error: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }
    else if (0 == child)
    {
        printf("fork_wrapper: fork(): succeeded (child)\n");
        exit(EXIT_SUCCESS);
    }
    else
    {
        printf("fork_wrapper: fork(): succeeded (parent)\n");
        return child;
    }
}

==> main.c <==
// To compile: gcc -L. -lfork_wrapper main.c -o main
#include "fork_wrapper.h"
#include <stdio.h>

int main(int argc, const char** argv)
{
    pid_t child = fork_wrapper();
    if (!child)
    {
        printf("fork_wrapper: waiting for child process\n");
        waitpid(-1, 0, 0);
    }

    return 0;
}

如果在共享库中调用 exit 并且共享库已被另一个程序加载,则 exit 会关闭所有内容,这不是一个好结果。