linux編程筆記,進程簡單例子

父進程中調用fork返回的是新子進程的PID。新進程將繼續執行,就象原進程一樣,只不過在子進程裏調用fork將返回 0 #include #include #include #include #include int main() { pid_t pid; char * message; int n; int exit_code; printf("fork program starting!/n"); pid = fork(); switch(pid) { case -1: perror("fork failed!/n"); exit( 1 ); case 0: message = "this is the child!/n"; printf("pid = %d/n",pid); n = 5; exit_code = 37; break; default: message = "this is parent!/n"; printf("pid = %d/n",pid); n = 3; exit_code = 0; break; } for(; n > 0; n--) { puts(message); sleep(1); } if(pid != 0) { int stat_val; pid_t child_pid; child_pid = wait(&stat_val); printf("child has finished: PID = %d/n",child_pid); if( WIFEXITED(stat_val) ) { printf( "Child exited with code: %d/n", WEXITSTATUS(stat_val) ); } else { printf("Child terminated abnormally!/n"); } } exit(exit_code); } 程序在調用fork的時候被分成兩個獨立的進程,程序根據fork的非零返回直確定父進程,父進程設置了一個消息輸出次數,兩次輸出之間間隔一秒 fork方法是以個單調用雙返回的函數。 在父進程中返回的是該創建的子進程的進程標識號 在子進程中返回的是0, 創建不成工,返回-1 反正夠繞的,多作,多想,多動手理解就好了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章