精華區beta Programming 關於我們 聯絡資訊
※ 引述《minhong.bbs@ptt.cc (minhong)》之銘言: > ※ 引述《mingchieh.bbs@bbs.cis.nctu.edu.tw (Bug J.)》之銘言: > : getppid() -> get parent pid > it works, but not always . > 程式碼: > #include <stdio.h> > #include <unistd.h> > int main() > { > if ( fork() == 0 ) > { > printf("PID of child process is %d.\n", getpid() ); > printf("PID of my parent is %d.\n", getppid() ); > } > else > { > printf("PID of parent process is %d.\n", getpid() ); > } > return 0 ; > } > 執行結果: > (正確) > PID of child process is 20107. > PID of my parent is 20106. > PID of parent process is 20106. > (出問題) > PID of parent process is 20110. > PID of child process is 20111. > PID of my parent is 1. 其實看到 pid 是 1 的時候就要有感覺了, 書上應該有說過 parent 要是結束而 child 沒結束的話, child 會被 init 認養這件事吧。 當你的 child 執行到 getppid() 時, 你的 parent 已經結束了, 就會發生這種現象, 不過這也屬於正常現象, 不能稱之為不 work。 -- Name: Tseng, Ling-hua E-mail Address: uranus@it.muds.net School: National Tsing Hua University Department: Computer Science Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design Researching: Undecided Homepage: https://it.muds.net/~uranus -- ╔═══╗ ┼────────────────────────╮ 狂狷 Origin:[ 狂 狷 年 少 ] whshs.cs.nccu.edu.tw ╰─╮ 年少 ┼╮ < IP:140.119.164.252 > ╰─╮ ╚╦═╦╝ From:61-230-216-250.dynamic.hinet.net ─╨─╨─ KGBBS 遨翔"BBS"的狂狷不馴;屬於年少的輕狂色彩 [修改]tinlans:61-230-216-250.dynamic.hinet.net 06/10/21 23:23:38