【发布时间】:2011-07-18 20:26:26
【问题描述】:
基于此http://man7.org/tlpi/code/online/dist/procexec/fork_sig_sync.c.html
/* fork_sig_sync.c
Demonstrate how signals can be used to synchronize the actions
of a parent and child process.
*/
#include <signal.h>
#include "curr_time.h" /* Declaration of currTime() */
#include "tlpi_hdr.h"
#define SYNC_SIG SIGUSR1 /* Synchronization signal */
static void /* Signal handler - does nothing but return */
handler(int sig)
{
}
int
main(int argc, char *argv[])
{
pid_t childPid;
sigset_t blockMask, origMask, emptyMask;
struct sigaction sa;
setbuf(stdout, NULL); /* Disable buffering of stdout */
sigemptyset(&blockMask);
sigaddset(&blockMask, SYNC_SIG); /* Block signal */
if (sigprocmask(SIG_BLOCK, &blockMask, &origMask) == -1)
errExit("sigprocmask");
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = handler;
if (sigaction(SYNC_SIG, &sa, NULL) == -1)
errExit("sigaction");
switch (childPid = fork()) {
case -1:
errExit("fork");
case 0: /* Child */
/* Child does some required action here... */
printf("[%s %ld] Child started - doing some work\n",
currTime("%T"), (long) getpid());
sleep(2); /* Simulate time spent doing some work */
/* And then signals parent that it's done */
printf("[%s %ld] Child about to signal parent\n",
currTime("%T"), (long) getpid());
if (kill(getppid(), SYNC_SIG) == -1)
errExit("kill");
/* Now child can do other things... */
_exit(EXIT_SUCCESS);
default: /* Parent */
/* Parent may do some work here, and then waits for child to
complete the required action */
printf("[%s %ld] Parent about to wait for signal\n",
currTime("%T"), (long) getpid());
sigemptyset(&emptyMask);
if (sigsuspend(&emptyMask) == -1 && errno != EINTR) // <<<<< Question
errExit("sigsuspend");
printf("[%s %ld] Parent got signal\n", currTime("%T"), (long) getpid());
/* If required, return signal mask to its original state */
if (sigprocmask(SIG_SETMASK, &origMask, NULL) == -1)
errExit("sigprocmask");
/* Parent carries on to do other things... */
exit(EXIT_SUCCESS);
}
}
问题
父进程调用sigsuspend时,为什么不验证发送的信号是SYNC_SIG?
http://pubs.opengroup.org/onlinepubs/7908799/xsh/sigsuspend.html
【问题讨论】:
-
一般来说,信号是一种可怕的进程间同步机制。我会忘记为此使用信号。在进程之间进行同步的最简单方法是使用管道。在同一进程的线程之间,使用屏障或信号量。
-
作为本主题的初学者,这里的问题是理解这段代码,而不是找出完成这项任务的最佳方法。
-
是的,我作为评论而不是答案发布,因为我知道我要说的并没有真正回答你的问题。我漫不经心地查看了代码,并没有立即发现问题所在,但我怀疑这是一些小细节。
标签: c linux multiprocessing ubuntu-10.04