具有多个进程的文件操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了具有多个进程的文件操作相关的知识,希望对你有一定的参考价值。

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

sample.txt:

A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72

如何使流程遵循它们保留的点?

答案

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

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

以上是关于具有多个进程的文件操作的主要内容,如果未能解决你的问题,请参考以下文章

在 Android 中使用具有多个布局的单个片段

具有相同布局的多个片段

python中的多线程和多进程编程

具有多个 backstack 的片段

从单个按钮从多个片段中提取数据

互斥与同步