gpt4 book ai didi

c - 如果两个进程都在执行同一个程序,是否可以在没有 exec 的情况下使用 fork?

转载 作者:行者123 更新时间:2023-12-01 13:43:41 25 4
gpt4 key购买 nike

这是一个代码示例,其中 fork 库调用用于创建共享父进程地址空间的子进程。子进程在不使用 exec 系统调用的情况下执行其代码。我的问题是:在父进程和子进程都在执行同一个程序的情况下,是否不需要 exec 系统调用?

  #include <stdio.h>
int main()
{
int count;
count = fork();
if (count == 0)
printf("\nHi I'm child process and count =%d\n", count);
else
printf("\nHi I'm parent process and count =%d\n", count);
return 0;
}

最佳答案

这个问题的答案可能因操作系统而异。 OS X 上 fork 的手册页包含这个不祥的警告(粗体部分是原文的释义):

There are limits to what you can do in the child process. To be totally safe you should restrict yourself to only executing async-signal safe operations until such time as one of the exec functions is called. All APIs, including global data symbols, in any framework or library should be assumed to be unsafe after a fork() unless explicitly documented to be safe or async-signal safe. If you need to use these frameworks in the child process, you must exec. In this situation it's reasonable to exec another copy of the same executable.

可以在 sigaction(2) 的手册页中找到异步信号安全函数的列表。

关于c - 如果两个进程都在执行同一个程序,是否可以在没有 exec 的情况下使用 fork?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649490/

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