- 論壇徽章:
- 0
|
回復(fù) 3# super皮波
寫了代碼測(cè)試了一下,這是fork之后把標(biāo)準(zhǔn)輸出重定向到一個(gè)hello文件- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
- int main(void)
- {
- pid_t pid;
- int fd1, i = 1;
- pid = fork();
- if(pid < 0)
- {
- perror("fork");
- exit(1);
- }
- else if(pid == 0)
- {
- while(1)
- {
- printf("write %d by child\n",i++);
- sleep(1);
- }
- }
- else
- {
- sleep(10);
- fd1 = open("hello",O_CREAT | O_RDONLY | O_WRONLY | O_APPEND,0755);
- if(fd1 < 0)
- {
- perror("open");
- exit(1);
- }
- dup2(fd1,STDOUT_FILENO);
- while(1)
- {
- printf("write %d by parent\n",i++);
- }
- }
- return 0;
- }
復(fù)制代碼 這個(gè)是在fork之前把標(biāo)準(zhǔn)輸出重定向到hello文件- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
- int main(void)
- {
- pid_t pid;
- int fd1, i = 1;
- fd1 = open("hello",O_CREAT | O_RDONLY | O_WRONLY | O_APPEND,0755);
- if(fd1 < 0)
- {
- perror("open");
- exit(1);
- }
- dup2(fd1,STDOUT_FILENO);
- pid = fork();
- if(pid < 0)
- {
- perror("fork");
- exit(1);
- }
- else if(pid == 0)
- {
- while(1)
- {
- printf("write %d by child\n",i++);
- usleep(10000);
- }
- }
- else
- {
- sleep(5);
- while(1)
- {
- printf("write %d by parent\n",i++);
- usleep(10000);
- }
- }
- return 0;
- }
復(fù)制代碼 剛開始的時(shí)候一直不太理解 |
|