C语言 为什么在UNIX中,父进程的执行总是晚于它在不使用wait()的情况下创建的子进程?

vuktfyat  于 2023-02-18  发布在  Unix
关注(0)|答案(1)|浏览(124)

我有个家庭作业问题:
Q7:执行下面代码后,会生成一个新的文件myFile.txt,myFile.txt中的内容会一致吗?为什么?代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
    printf("hello world (pid:%d)\n", (int)getpid());
    int fd = open("myFile.txt", O_CREAT|O_RDWR);
    if(fd == -1 ) {
        printf("Unable to open the file\n exiting....\n");
        return 0;
    }
    
    int rc = fork();
    
    
    if (rc < 0) {
        fprintf(stderr, "fork failed\n");
        exit(1);
    }
    else if (rc == 0) {
        printf("hello, I am child (pid:%d)\n", (int)getpid());
        char myChar='a';
        write(fd, &myChar,1);
        printf("writing a character to the file from child\n");
    }
    else {
        printf("hello, I am parent of %d (pid:%d)\n",
               rc, (int)getpid());
        char myChar='b';
        write(fd, &myChar,1);
        printf("writing a character to the file from parent\n");
    }
return 0;
}

父进程将“a”写入myFile.txt,而子进程将“B”写入该文件。我多次执行此程序,发现txt文件一致为“ba”,这意味着父进程总是在子进程之后。但是,我注意到父进程没有调用wait()函数。有人能解释一下为什么父进程在子进程之后吗?

hsvhsicv

hsvhsicv1#

并发任务的顺序是由操作系统定义的实现。如果需要,您需要使用同步原语来确保定义良好的操作顺序(文件锁、管道、互斥体、条件变量、信号量等)。

相关问题