我想創建一個使用fork()創建新進程的程序。示例輸出應如下所示:fork()子進程和父進程
這是子進程。我的pid是733,父母的ID是772.
這是父進程。我的pid是772和我的孩子的id是773
這是我如何編碼的我的程序:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), fork());
return 0;
}
這將導致輸出:
這是孩子的過程。我的pid是22163,父母的ID是0.
這是子進程。我的pid是22162,我的父母的編號是22163.
爲什麼打印語句兩次,以及如何在第一個句子顯示子標識後正確顯示父母的ID?
編輯:
#include <stdio.h>
#include <stdlib.h>
int main() {
int pid = fork();
if (pid == 0) {
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
else {
printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid);
}
return 0;
}
您的程序不會嘗試在任何地方打印單詞「父進程」。它們不在節目文本中,你爲什麼期望它們被打印? –
'人叉'。閱讀。理解單詞。如果您沒有任何方法可以自己查找答案,請轉到StackOverflow。你將成爲這種體驗的更好的程序員。 – asveikau
另外,'fork'不會將父進程ID返回給子進程。它返回0給孩子和孩子的ID給父母。這就是你如何知道哪個是哪個。 –