#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
int main(void) {
pid_t child_pids[4] = { 0 };
int events[4] = { -1 };
int back_events[4] = { -1 };
for (int i = 0; i < 4; ++i) {
const int event_fd = eventfd(0, 0);
const int back_event_fd = eventfd(0, 0);
const pid_t pid = fork();
if (pid == 0) {
eventfd_t value;
eventfd_read(event_fd, &value);
printf("Output from process %d\n", getpid());
eventfd_write(back_event_fd, value);
exit(0);
} else if (pid > 0) {
child_pids[i] = pid;
events[i] = event_fd;
back_events[i] = back_event_fd;
printf("Forked process %d\n", pid);
} else {
perror("fork");
}
}
eventfd_t value = 1;
/* This loop signals the processes in a sequential order */
for (int i = 0; i < 4; ++i) {
eventfd_write(events[i], value);
eventfd_read(back_events[i], &value);
}
pid_t wpid;
while ((wpid = wait(NULL)) > 0) {
printf("Process %d terminated\n", wpid);
}
return 0;
}
我的系统上的输出:
Forked process 20795
Forked process 20796
Forked process 20797
Forked process 20798
Output from process 20795
Output from process 20796
Output from process 20797
Output from process 20798
Process 20795 terminated
Process 20796 terminated
Process 20797 terminated
Process 20798 terminated
1条答案
按热度按时间kyvafyod1#
只有父进程应该在其子进程上调用
wait
或waitpid
,以获取它们的终止状态。为了在子进程之间强制执行某种特定的执行顺序,您需要某种IPC机制。这可能是从父进程调度的事件。我会使用Linux特定的
eventfd
API(用于在进程之间发送事件信号的文件描述符)编写类似的代码:我的系统上的输出:
在
eventfd
调用周围添加一些额外的错误检查也不会有什么坏处。