我正在大学学习操作系统课程。 有多种方法可以使用 wait() 系统调用和 vfork() 确保子级首先执行(在父级之前)。
但是我没有找到一种方法来确保父进程首先执行(在子进程之前)。
我尝试使用 ussleep() 来延迟子进程,以便父进程首先执行,因为分时和现代处理器是多核的。 但我不认为这是一个可行的解决方案(我不确定它是否适用于所有系统)。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t child_pid, pid, parent_pid;
// Create a child process
pid = fork();
if (pid == -1) {
perror("Fork failed");
exit(1);
}
if (pid == 0) {
This is the child process
usleep(100000); // Add a small delay (1 millisecond) to allow the parent to run first
printf("Child\n");
} else {
// This is the parent process
printf("Parent\n");
}
return 0;
}
大多数计算机(甚至是 2023 年运行 Linux 的廉价笔记本电脑)都有多个核心。
事实上,父进程和子进程很可能同时在不同的内核上运行。
但是我没有找到一种方法来确保父进程首先执行(在子进程之前)。
实际上,这是不可能的。 两个进程同时运行。
您想要的是让这些进程通信或同步。
这可以使用多个系统调用来实现。 Linux 有数百个,在 syscalls(2) 中列出。
学习使用 pipe(2)、poll(2)、write(2)、read(2)、socket(2)、waitpid(2)、errno(3) ), proc(5), sem_overview(7), shm_overview(7), unix(7), signal(7), signal-safety(7), pthreads( 7)
研究使用 Linux 和流程的现有开源项目的源代码以获取灵感,例如GNU Bash、GNU Emacs、Z shell(可执行文件
zsh
)、GNU Make 或 RefPerSys 或数千种其他工具。