fork, exec, pipe
- UNIX(Linux)ã®ããã»ã¹èµ·å㯠createProcess ã¨ãããããª1ã¤ã®ã·ã¹ãã ã³ã¼ã«ã§ã¯ãªããfork 㨠exec ã®çµã¿åãã(Fork-Exec)ã§å®ç¾ãããã
- fork ã¯ç¾å¨ã®ããã»ã¹ãã¾ãã¾ãã³ãã¼ããå¥ã
ã®å®è¡ã³ã³ããã¹ããä½ãã
- fork ã¸ã®æ»ãå¤ãããããã®ã³ã³ããã¹ãã§å¤ãã¦åºå¥ãããã
- ä»®æ³ã¡ã¢ãªç©ºéã®æ å ±ãã³ãã¼ãããã
- exec ã¯èªããã»ã¹ãå¥ã®ãã¤ããªå®è¡ç¨ããã»ã¹ã«ç½®ãæããã
- fork 㨠exec ãåããã¦ããããã¤ãfork ã親ããã»ã¹ã®ä»®æ³ã¡ã¢ãªç©ºéãã³ãã¼ãã¦ãããã¨ã§ã親ããã»ã¹ã¨åããã»ã¹(ã¾ãã¯åããã»ã¹å士)ã®éã®éä¿¡ç¨ã®ãã¤ããä½ãå¦çã fork 㨠exec ã®éã§è¡ããã¨ãã§ããã
ãforkããããªã¼ç¾ç§äºå ¸ãã¦ã£ãããã£ã¢æ¥æ¬èªçããã
Fork-Execã¯ãUNIXã§ä¸è¬çã«ä½¿ãããææ³ã§ãããæ°ããªããã°ã©ã ãããã»ã¹ã¨ãã¦å®è¡ãããfork()ã¯è¦ªããã»ã¹ã2ã¤ã®åä¸å 容ã®ããã»ã¹ã«ï¼ãã©ã¼ã¯ã®å ã®ããã«ï¼åå²ãããã·ã¹ãã ã³ã¼ã«ã§ãããfork()ã«ãã£ã¦åããã»ã¹ã親ããã»ã¹ã®ã³ãã¼ã¨ãã¦çæãããexec()ã·ã¹ãã ã³ã¼ã«ãå¼ã³åºããã¨ã§ï¼åããã»ã¹ï¼èªèº«ã®å 容ãç½®ãæããã
åããã»ã¹ãexec()ãå¼ã³åºãã¨ããã®ã¢ãã¬ã¹ç©ºéã®å 容ã¯å ¨ã¦å¤±ãããæå®ãããããã°ã©ã ãå®è¡ããããã®ã¢ãã¬ã¹ç©ºéã®ãããã³ã°ãè¨å®ããããããããªã¼ãã¼ã¬ã¤ã¨å¼ã¶ãã¢ãã¬ã¹ç©ºéã¯å ¨ã¦ç½®ãæãããããããªã¼ãã³æ¸ã¿ãã¡ã¤ã«ã®ãã¡ã¤ã«è¨è¿°å群㯠close-on-exec ãæå®ãããã¨ãã ã exec()æã«èªåçã«ã¯ãã¼ãºãããããã®ç¹å¾´ãå©ç¨ãã¦ãfork()ãå¼ã³åºãåã«ãã¤ããä½æãã¦ãããexec()ã§æå®ãããæ°ããããã°ã©ã ã¨ã®éä¿¡ãè¡ãã¨ããUNIXç¹æã®ææ³ãå®ç¾ããã¦ããã
åä½ç¢ºèªç¨ã³ã¼ã(C++)
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<sys/wait.h> #define READ 0 #define WRITE 1 int pfd[2]; void doChildProcess() { char *argv[16]; close(pfd[WRITE]); dup2(pfd[READ], STDIN_FILENO); argv[0] = "/usr/bin/tr"; argv[1] = "[:lower:]"; argv[2] = "[:upper:]"; argv[3] = NULL; execv(argv[0], argv); } int main() { pid_t cpid; char *msg; if ( pipe(pfd) == -1 ) { perror("pipe"); exit(EXIT_FAILURE); } cpid = fork(); if ( cpid == -1 ) { perror("fork"); exit(EXIT_FAILURE); } if ( cpid == 0 ) doChildProcess(); // NEVER to return // doParentProcess... close(pfd[READ]); msg = "hello world!\n"; write(pfd[WRITE], msg, strlen(msg)); close(pfd[WRITE]); wait(NULL); exit(EXIT_SUCCESS); }