[原文]
fork()函數:用於創建子進程,子進程完全復制父進程的資源,相當於父進程的拷貝。具體理解,運用父進程的同一套代碼,通過判斷進程ID來執行不同進程的不同任務。
返回值正常為子進程ID,出錯返回負值。
pipe()函數:用於創建管道,返回負值表示創建失敗。
簡單實例:
功能:父進程通過管道向子進程傳遞字符串,然后子進程向屏幕打印出所收到的字符串。
- <pre class="objc" name="code">#include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
-
- int main(void)
- {
- int n,fd[2];
- pid_t pid;
- char line[1024];
-
- if (pipe(fd) < 0)
- return 1;
- if ((pid=fork()) < 0)
- return 1;
- else if (pid > 0) //parent
- {
- close(fd[0]); //close parent's read-port
- write(fd[1],"I am from parent!\n",19); //write to pipe
- }
- else //child
- {
- close(fd[1]); //close child's write-port
- n = read(fd[0],line,1024); //read from pipe
- printf("%s%d\n",line,n);
- }
- printf("I am public!\n");
- return 1;
- }
運行結果:
I am public!
I am from parent!
19
I am public!
通過上面實例,可以清楚認識父子進程運行情況;通過關閉父進程讀端口,關閉子進程寫端口實現數據由父進程傳向子進程的單向管道傳輸。