我正在尝试以下C代码:
int main()
{
printf("text1\n");
fork();
printf("text2\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我期待获得输出,我得到两个"text1"和两个"text2",如:
text1
text1
text2
text2
Run Code Online (Sandbox Code Playgroud)
但是,相反,我得到:
text1
text2
text2
Run Code Online (Sandbox Code Playgroud)
只有一个"text1"??? 好吧,如果子进程从fork()执行,那么为什么我得到两个"text1"表示以下内容:
int main()
{
printf("text1");
fork();
printf("text2\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在的输出是:
text1text2
text1text2
Run Code Online (Sandbox Code Playgroud)
如果子进程在fork之后启动,则输出应为:
text1
text2
text2
Run Code Online (Sandbox Code Playgroud) 我注意到我可以访问子进程函数/目标之外的子进程中的函数和模块。所以我想知道当我在 python 中创建一个子进程时,它是否从当前进程中复制了所有内容?为什么我可以访问子目标之外的函数和导入的模块?
from multiprocessing import Process, Pipe
def test1():
return "hello"
def simpleChildProcess( childPipe ):
# simpleChildProcess can access test1 function
foo = test1()
childPipe.send( foo )
parentPipe, childPipe = Pipe()
childProcess = Process( target=simpleChildProcess, args=(childPipe,) )
childProcess.start()
print "Pipe Contains: %s" % parentPipe.recv()
Run Code Online (Sandbox Code Playgroud)