【发布时间】:2019-05-13 00:39:11
【问题描述】:
我很难同步 N 个子进程,等待它们中的每一个到达某个特定点。 我已经尝试过信号量和信号,但我无法理解它。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/msg.h>
#define NUM_KIDS 4
void handle(int signum);
int main(int argc, char const *argv[])
{
sem_t* sem;
sem = sem_open("/ok", O_CREAT, 0);
signal(SIGUSR1, handle);
for(int i = 0; i < NUM_KIDS; i++) {
switch(fork()) {
case 0:
fprintf(stderr, "ready %d from %d\n", getpid(), getppid());
/* i would like that each child stop here untill everyone is ready */
for(int j = 0; j < 10; j++)
fprintf(stderr, "lot of stuff\n");
exit(0);
break;
default:
/* unleashing the kids when everyone is ready */
wait(NULL);
fprintf(stderr, "OK\n");
break;
}
}
return 0;
}
void handle(int signum) {;}
而且我相信输出应该是(一旦孩子同步)
ready ... from xxx
ready ... from xxx
ready ... from xxx
ready ... from xxx
...lots of stuff... 10 times
...lots of stuff... 10 times
...lots of stuff... 10 times
...lots of stuff... 10 times
【问题讨论】:
-
您的“几乎但不完全是 MCVE (minimal reproducible example)”代码中有许多多余的标头和一些多余的代码。信号量和信号代码似乎无关紧要。
-
我尝试了很多解决方法,让它们放在那里更容易
-
当你在你的机器上玩的时候这很好——当你在 SO 上提问时就不行了。你在 SO 上展示的代码应该是一个 MCVE——最小意味着“没有多余的代码”。
标签: c unix synchronization fork ipc