标签: shared-file

父子进程使用的文件

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>


int main( int argc, char *argv[] ){


    FILE *fptr;
    pid_t pid;

    fptr = fopen("Shared File.txt", "a");
    pid = fork();

    if( pid > 0 ){ // parent process

        int counter = 0;

        while( counter < 10 ){
            fprintf(fptr, "a");
            ++counter;
        }
        wait(NULL);
    }
    else{

        int counter = 0;

        while( counter < 5 ){
            fprintf(fptr, "b");
            ++counter;
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我执行此代码时,代码生成的文件包含此消息:bbbbbaaaaaaaaaa

每当我执行此代码时,都会收到相同的消息。为什么进程不以混洗顺序写入文件?

为什么操作系统首先尝试完成子进程?

我对消息的期望是这样的: baabbaaabaaabaa 进程之间没有连续的过渡。

process shared-file

2
推荐指数
1
解决办法
1021
查看次数

标签 统计

process ×1

shared-file ×1