先打印“parent”,後打印“child”
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sched.h>
#define STACK_SIZE (1024 * 1024)
int child(void *arg) {
int efd = *((int*)arg);
// 等待父進程的通知
uint64_t u;
ssize_t ret;
ret = read(efd, &u, sizeof(uint64_t));
if (ret != sizeof(uint64_t)) {
printf("child error\n");
}
printf("child\n");
return 0;
}
int main() {
int efd = eventfd(0, 0);
if (efd < 0) {
printf("create eventfd error\n");
return -1;
}
char *stack = malloc(STACK_SIZE);
char *stackTop = stack + STACK_SIZE;
clone(child, stackTop, SIGCHLD, (void*)(&efd));
printf("parent\n");
// 通知子進程
ssize_t ret = write(efd, &(uint64_t){1}, sizeof(uint64_t));
if (ret != sizeof(uint64_t)) {
printf("parent error\n");
return -1;
}
}
結果:
parent
child
參考
https://zhuanlan.zhihu.com/p/40572954