【问题标题】:Executing the program after the "fork part"在“fork 部分”之后执行程序
【发布时间】:2017-09-22 22:58:14
【问题描述】:

在我的程序中,我在 main 函数中使用 fork 来创建 2 个进程。子进程做某事,父进程再次分叉,他的子进程调用另一个函数。两个函数都写入 1 个文件,一切正常。 我需要的是在两个函数和所有进程(两个函数都创建进程)完成后在文件末尾写一些东西。 我试图在 main 中的任何地方编写 fprintf 命令,它总是写在文件中间的某个地方,所以我认为 main 可能与 2 个函数并行运行。 我尝试使用信号量 s = sem_open(s1, o_CREATE, 0666, 0); 这样:在每个函数的末尾我写了sem_post(s),在main中我写了sem_wait(s); sem_wait(s);,之后我写了fprintf命令,但它也没有用。 有什么办法可以解决这个问题吗? 谢谢

【问题讨论】:

  • 使用fork 不是并行处理 - 这是不正确的术语。

标签: c semaphore


【解决方案1】:

我认为您正在寻找wait 函数。请参阅this stack overflow questionwait(NULL)等待所有子进程完成等待子进程完成(感谢 Jonathan Leffler)。在循环中调用wait 以等待所有子进程完成。只需在写入父进程中的文件之前使用该函数即可。

如果您想等待特定进程而不是所有进程,您还可以阅读waitpid 函数。

编辑: 或者,您实际上可以跨进程使用信号量,但这需要更多的工作。见this stack overflow answer。基本思想是将函数sem_openO_CREAT 常量一起使用。 sem_open 有 2 个函数签名:

sem_t *sem_open(const char *name, int oflag);

sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);

来自sem_open man page

   If O_CREAT is specified in oflag, then two additional arguments must
   be supplied.  The mode argument specifies the permissions to be
   placed on the new semaphore, as for open(2).  (Symbolic definitions
   for the permissions bits can be obtained by including <sys/stat.h>.)
   The permissions settings are masked against the process umask.  Both
   read and write permission should be granted to each class of user
   that will access the semaphore.  The value argument specifies the
   initial value for the new semaphore.  If O_CREAT is specified, and a
   semaphore with the given name already exists, then mode and value are
   ignored.

在您的父进程中,使用 mode 和 value 参数调用 sem_open,为其提供您需要的权限。在子进程中,调用 sem_open("YOUR_SEMAPHORE_NAME", 0) 以打开该信号量以供使用。

【讨论】:

  • 可能有助于简要总结每个答案所传达的内容,而不是转储链接。
  • 我不确定,但我认为我拥有它与您所写的完全一样。我有它: main: sem_t *s; s = sem_open(s1, O_CREAT, 0666, 0); sem_close(s); s = sem_open(s1, O_RDWR);函数一和二:sem_t *s; s = sem_open(s1, O_RDWR); "s1" 是一个宏。
  • 请注意wait() 等待一个孩子死亡。您必须循环使用它来等待所有孩子死亡。 int corpse; int status; while ((corpse = wait(&amp;status)) != -1) printf("PID %d exited with status 0x%.4X\n", corpse, status);。仍然存在对信号处理等方面的担忧;如果你愿意,你可以让它更复杂。
猜你喜欢
  • 2021-12-08
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2018-02-04
  • 2014-07-04
相关资源
最近更新 更多