Perl 程式設計/關鍵字/fork
外觀
fork建立一個fork(2)呼叫以在相同點啟動相同程式,將子程序 PID 返回給其父程序,0給子程序,或undef,如果它不成功。檔案描述符有時與它們的鎖共享,而其他所有內容都被複制。大多數支援fork()的系統以極高的效率實現了它。
Perl 嘗試在派生子程序之前重新整理所有開啟的輸出檔案,但這可能不受某些平臺支援。為了安全起見,您可能需要設定$| ($AUTOFLUSH(以英語)或呼叫autoflush()方法IO::Handle在所有開啟的控制代碼上,以避免重複輸出。
要fork而不等待子程序會建立殭屍程序。在某些平臺(如 Windows)上,fork()系統呼叫不可用,Perl 可以構建成在 Perl 直譯器中模擬它。
fork
$pid = fork();
if ($pid == 0) {
print "I am the child of my parent\n";
exit 0;
}
print "I am the parent process and have the child with the ID $pid\n";
exit 0;
返回
I am the parent process and have the child with the ID -6852 I am the child of my parent