黑馬《linux系統程式設計》學習筆記(從21到25)
阿新 • • 發佈:2018-12-29
二十一. 複習
二十二. 父子程序間使用檔案進行通訊
這裡的重點,在於理解,fork完了之後,父程序裡的檔案描述符,也會做相應的複製。比如父程序的3號檔案描述符指向temp這個檔案,那麼子程序的3號檔案描述符,也會指向temp這個檔案
process_file.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <fcntl.h> // 操作終端檔案 /dev/tty預設阻塞 int main(int argc, const char* argv[]) { int fd = open("temp", O_CREAT | O_RDWR, 0664); if(fd == -1) { perror("open error"); exit(1); } pid_t pid = fork(); if(pid == -1) { perror("fork error"); exit(1); } if(pid > 0) { char* p = "近期,微軟向Linux開發人員伸出了橄欖枝,希望Linux開發人員能夠轉移到Windows 10平臺上進行開發。"; write(fd, p, strlen(p)+1); close(fd); } else if(pid == 0) { // 睡1s保證父程序已經完成了檔案的寫操作 sleep(1); char buf[1024]; lseek(fd, 0, SEEK_SET); int len = read(fd, buf, sizeof(buf)); printf("%s\n", buf); close(fd); } return 0; }
二十三. 檔案
multi_process.c
#include <stdio.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(int argc, const char* argv[]) { int num = 3; int i = 0; pid_t pid; for(i=0; i<num; ++i) { pid = fork(); if(pid == 0) { break; } } if(i == 0) { execlp("ps", "ps", "aux", NULL); perror("execlp ps"); exit(1); } else if(i == 1) { execl("/home/kevin/test/app", "app", NULL); perror("execl app"); exit(1); } else if(i == 2) { execl("./error", "error", NULL); perror("execl error"); exit(1); } else if(i == num) { // 回收 int status; pid_t wpid; //下一行,與這一行的寫法等價 while( (wpid = wait(&status)) != -1 ) while( (wpid = waitpid(-1, &status, WNOHANG)) != -1 ) { printf(" ----- child died pid = %d\n", wpid); if(WIFEXITED(status)) { printf("return value %d\n", WEXITSTATUS(status)); } else if(WIFSIGNALED(status)) { printf("died by signal: %d\n", WTERMSIG(status)); } } } return 0; }
二十四. waitpid函式
以下圖裡,A本來有1,2,3,4共四個子程序。然後我們把A的4號程序,送給了B程序。在這樣的情況下。函式waitpid中如果pid==0,那麼並不能影響到B中的4號程序,因為並不在同一個組裡了。
二十五. IPC的概念