我對 unix 編程很陌生,遇到了一些我不明白的事情。這是以下代碼片段:
#include <stdio.h>
#include <sys/types.h>
int main()
{
printf("%d ", fork());
return 0;
}
輸出是:9298 0。為什么子行程呼叫這個printf?在我的課程中,我被告知它會在fork()呼叫后執行所有操作。我怎么了?
uj5u.com熱心網友回復:
當子行程啟動時,它會從fork呼叫的確切位置開始,也就是在printf呼叫程序中。
所以現在父行程和子行程都將完成自己單獨的printf呼叫,每個都輸出自己的回傳值。
uj5u.com熱心網友回復:
的結果fork被傳遞給printf所以它在之前執行printf。您的代碼相當于:
#include <stdio.h>
#include <sys/types.h>
int main()
{
pid_t pid = fork();
printf("%d ", pid);
return 0;
}
uj5u.com熱心網友回復:
你被告知的是不準確的。發生的情況是 a fork是行程的(幾乎相同的)副本。
所以它繼續 fork() 回傳父級和子級中的值。并printf在這兩個程序中繼續。
想想正在運行的程式創建了一個克隆(這個解釋有點諷刺,我稍后會談到;))它自己和兩個從那時起在病房里做同樣的事情。從程式的內部角度來看,唯一的區別是作業系統為每個副本提供的回傳值。父程式接收子程式的行程 ID (pid),而子程式接收0. 這樣他們就可以很容易地將自己區分開來。
來自 fork 手冊頁的片段:
下面的代碼片段顯示了有關“父”和“子”行程之間差異的更多詳細資訊:
fork() creates a new process by duplicating the calling process.
The new process is referred to as the child process. The calling
process is referred to as the parent process.
The child process and the parent process run in separate memory
spaces. At the time of fork() both memory spaces have the same
content. Memory writes, file mappings (mmap(2)), and unmappings
(munmap(2)) performed by one of the processes do not affect the
other.
The child process is an exact duplicate of the parent process
except for the following points:
* The child has its own unique process ID, and this PID does not
match the ID of any existing process group (setpgid(2)) or
session.
* The child's parent process ID is the same as the parent's
process ID.
* The child does not inherit its parent's memory locks
(mlock(2), mlockall(2)).
* Process resource utilizations (getrusage(2)) and CPU time
counters (times(2)) are reset to zero in the child.
* The child's set of pending signals is initially empty
(sigpending(2)).
* The child does not inherit semaphore adjustments from its
parent (semop(2)).
* The child does not inherit process-associated record locks
from its parent (fcntl(2)). (On the other hand, it does
inherit fcntl(2) open file description locks and flock(2)
locks from its parent.)
* The child does not inherit timers from its parent
(setitimer(2), alarm(2), timer_create(2)).
* The child does not inherit outstanding asynchronous I/O
operations from its parent (aio_read(3), aio_write(3)), nor
does it inherit any asynchronous I/O contexts from its parent
(see io_setup(2)).
在 Linux 中克隆
如果您使用的是 Linux,則 fork() 呼叫是clone()系統呼叫的包裝器(實際上是一個子集)。有關更多資訊,請參閱:
https://man7.org/linux/man-pages/man2/clone.2.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367748.html
上一篇:如何使用JavaPrintWriter將void型別方法的結果列印到檔案中
下一篇:兩次呼叫函式并每次保存不同的值
