【发布时间】:2018-03-04 10:41:00
【问题描述】:
实际上,我正在尝试访问两个不同进程中的文件,其中一个是父进程,另一个是子进程。他们能够访问该文件并读取其内容。我的期望是该过程继续从另一个文件保留的位置读取文件。例如,父进程读取前两行。之后,子进程开始读取第 5 行、第 6 行、第 7 行和第 8 行。但是,它们并没有像我预期的那样运行。
exec.c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void){
pid_t pidValue = fork();
if( pidValue == -1 ){
printf("Creating new process failed\n");
}
else if( pidValue == 0 ){
printf("Child Process ID = %d\n", getpid());
printf("Parent Process ID = %d\n", getppid());
execlp("./test", "U", "N", "I", "X", (char*)NULL);
sleep(5);
}
else{
printf("This is parent process : \n");
printf("\tChild Process ID = %d\n", pidValue);
printf("\tParent Process ID = %d\n", getpid());
FILE *fptr = fopen("sample.txt", "r");
int x = 0;
char *name = malloc(sizeof(char) * 12);
int age;
while( x < 4 ){
fscanf(fptr, "%s %d", name, &age);
printf("%s %d\n", name, age);
++x;
}
wait(NULL);
}
return 0;
}
test.c:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] ){
int x = 0;
while( x < argc ){
printf("%s", argv[x++]);
}
printf("\n");
FILE *fptr = fopen("sample.txt", "r");
int i = 0;
int age;
char *name = malloc(sizeof(char) * 12);
while( i < 4 ){
fscanf(fptr, "%s %d", name, &age);
printf("%s %d\n", name, age);
++i;
}
return 0;
}
示例.txt:
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
我怎样才能使流程遵循它们所在的点?
【问题讨论】:
-
每个进程都有自己的文件指针。