为什么在UNIX中,如果没有使用wait(),父进程总是在子进程之后执行?

huangapple go评论54阅读模式
英文:

Why does the parent process always executes later than the child process it creates without wait() in UNIX?

问题

根据您提供的信息,父进程将"a"写入myFile.txt,而子进程将"b"写入该文件。您多次执行此程序,发现文本文件一直是"ba",这意味着父进程始终在子进程之后执行。但是,您注意到父进程没有调用wait()函数。有人能解释为什么父进程在子进程之后执行吗?

根据代码和描述,这是因为操作系统的调度机制。在fork()之后,操作系统决定哪个进程首先运行。通常情况下,父进程和子进程的执行顺序是不确定的,取决于操作系统的调度策略。父进程和子进程之间的执行顺序可能会因为各种因素而变化,包括系统负载、进程优先级等。

在您的情况下,父进程和子进程都尝试写入文件myFile.txt。由于文件操作是一种共享资源,操作系统会根据其调度策略来决定哪个进程首先获得写入权限。因此,即使父进程在代码中出现在子进程之前,实际执行顺序可能会有所不同。

要实现明确定义的执行顺序,您可以使用进程同步机制,如信号量或互斥锁,以确保父进程在子进程之后执行。如果不使用这些机制,您不能依赖于操作系统的调度来保证执行顺序。

英文:

I have a homework question:
> Q7: After executing the following code, a new file named myFile.txt is generated. Is the content in myFile.txt will be consistent? Why?
And here is the code:

#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;
}

The parent will write "a" into myFile.txt while the child writes "b" into that file. I executed this program several times, finding the txt file consistent being "ba", meaning that the parent always comes after the child. However, I noticed that there's no wait() function called by the parent process. Can someone explain why the parent comes after the child?

答案1

得分: 1

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

英文:

The order of concurrent tasks are implementation defined by the OS. You need to use synchronization primitives to ensure a well defined order of actions if required (file locks, pipes, mutex, condition variables, semaphores etc).

huangapple
  • 本文由 发表于 2023年2月16日 17:04:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定