c - 多进程文件操作

标签 c file-io process exec

实际上,我正在尝试访问两个不同进程中的文件,第一个是父进程,另一个是子进程。他们能够访问该文件并读取其内容。我的期望是该进程继续从另一个文件剩余的位置读取该文件。例如,父进程读取前两行。之后,子进程开始读取第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;
}

测试.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

如何使流程遵循它们所处的位置?

最佳答案

文件指针与任何其他指针不同。因此,您不能增加文件指针以指向文件中的特定行。每次使用 gets() 调用时,它都会读取它指向的行。所以你不能在你目前正在尝试的两个不同的过程中这样做。但是您可以通过共享全局文件指针来使用多线程来实现它。但文件读取方法必须通过同步,否则多个线程可能最终从文件中读取同一行。

此外,当您使用 fork() 调用时,它会将所有数据、内存地址复制到其子进程,这些数据将成为该进程的本地进程。因此,您指的是主进程的文件指针和子进程中的文件指针是不同的。因此,在一个进程中操作文件指针永远不会影响另一进程中的文件指针。

关于c - 多进程文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49094496/

相关文章:

C# 使用多个参数启动应用程序

java - Process.getOutputStream() 不起作用?

C、在结构体中设置变量

Java读取文件并将文本存储在数组中

mysql - 错误代码 : 1148. 此 MySQL 版本不允许使用的命令

Python字符串处理优化

.net - 从 .NET 程序与 ffmpeg 交互?

c - 我无法使用 scanf 将名称输入到 char 数组中

c - libc.so 在一个进程中映射了四个段,为什么?

控制台应用程序离开 cmd.exe 设置大小