close
Warning:
Can't synchronize with repository "(default)" (Unsupported version control system "svn": /usr/lib/python2.7/dist-packages/libsvn/_repos.so: failed to map segment from shared object: Cannot allocate memory). Look in the Trac log for more information.
- Timestamp:
-
Jan 13, 2009, 5:36:56 PM (16 years ago)
- Author:
-
wade
- Comment:
-
--
Legend:
- Unmodified
- Added
- Removed
- Modified
-
v6
|
v7
|
|
37 | 37 | |
38 | 38 | == Pipe == |
| 39 | * 範例: |
| 40 | {{{ |
| 41 | // parent process 借由 fork() 產生一個跟自己一樣的 child process |
| 42 | // 兩個 processes 間藉由 pipe 來傳遞資料 |
| 43 | // child → pipe → parent ,由 child 寫入資料至 pipe , parent 再由 pipe 接收資料並寫入 stdout |
| 44 | |
| 45 | #include <unistd.h> |
| 46 | #include <stdio.h> |
| 47 | |
| 48 | int main(void) |
| 49 | { |
| 50 | int n, fd[2]; |
| 51 | pid_t pid; |
| 52 | char line[255]; |
| 53 | |
| 54 | // 建立 pipe |
| 55 | // fd[1] → pipe → fd[0] |
| 56 | // pipe 的形勢與 FIFO 類似 |
| 57 | if (pipe(fd) < 0) |
| 58 | { |
| 59 | printf("Can't create pipe!\n"); |
| 60 | } |
| 61 | |
| 62 | // fork 創造一個 child process ,他與 parent 相同 |
| 63 | if ( (pid = fork()) < 0) |
| 64 | { |
| 65 | printf("fork error\n"); |
| 66 | } |
| 67 | else if (pid == 0) |
| 68 | { // child process = 0 |
| 69 | close(fd[0]); |
| 70 | // 將字串寫入 pipe 內 2 次 |
| 71 | write(fd[1], "hello world\n",12); |
| 72 | write(fd[1], "second time\n",12); |
| 73 | } |
| 74 | else |
| 75 | { // parent process |
| 76 | close(fd[1]); |
| 77 | n = read(fd[0], line, 255); |
| 78 | // 將結果寫出到 FD=1 (stdout) |
| 79 | write(1,line,n); |
| 80 | write(1,line,n); |
| 81 | |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | }}} |
39 | 86 | * FD[0] 負責 read pipe。FD[1] 負責 write pipe。 |
40 | 87 | FD[1] → [PIPE] → FD[0]。 |