- 論壇徽章:
- 0
|
文件123.txt內(nèi)容:
123
234
345
代碼如下:- #include <stdio.h>
- #include <string.h>
- #include <sys/types.h>
- #include <unistd.h>
- int main(void)
- {
- int i;
- pid_t pid;
- FILE *fp;
- fp = fopen("123.txt", "r");
- char buf[100];
- memset(buf, 0, sizeof(buf));
- printf("%d, file pos:[%d]\n", getpid(), ftell(fp));
- for (i = 0; i < 2; i++)
- {
- pid = fork();
- if (pid == 0)
- {
- char bufx[100];
- memset(bufx, 0, sizeof(bufx));
- printf("%d, file pos:[%d]\n", getpid(), ftell(fp));
- fgets(bufx, 100, fp);
- bufx[strlen(bufx)-1] = 0;
- printf("%d, bufx=[%s]\n", getpid(),bufx);
- if (i == 0)
- {
- sleep(2);
- }
- fgets(bufx, 100, fp);
- bufx[strlen(bufx)-1] = 0;
- printf("%d, bufx=[%s]\n", getpid(), bufx);
- return 0;
- }
- }
- sleep(10);
- printf("%d, file pos:[%d]\n", getpid(), ftell(fp));
- while (fgets(buf, 100, fp))
- {
- buf[strlen(buf)-1] = 0;
- printf("buf=[%s]\n", buf);
- memset(buf, 0, sizeof(buf));
- }
- fclose(fp);
- return 0;
- }
復(fù)制代碼 期待讀取文件輸出的結(jié)果:
進程1:
123
234
進程2:
123
234
主進程:
123
234
345
單成型打印的結(jié)果卻是:
14796, file pos:[0]
14797, file pos:[0]
14797, bufx=[123]
14798, file pos:[0]
14798, bufx=[]
14798, bufx=[]
14797, bufx=[234]
14796, file pos:[0]
進程間讀取文件會互相影響文件的當(dāng)前位置嗎? 就算這樣,進程2也應(yīng)該有內(nèi)容讀取到,打印出來, 不明白輸出的結(jié)果為什么是這樣的 |
|