- 论坛徽章:
- 0
|
文件123.txt内容:
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;
- }
复制代码 期待读取文件输出的结果:
进程1:
123
234
进程2:
123
234
主进程:
123
234
345
单成型打印的结果却是:
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]
进程间读取文件会互相影响文件的当前位置吗? 就算这样,进程2也应该有内容读取到,打印出来, 不明白输出的结果为什么是这样的 |
|