之后执行程序,我在主函数fork中使用来创建2个进程。子进程做一些事情,父进程再次分叉,他的孩子调用另一个函数。两个函数都写入1个文件,并且所有工作都正常。 我需要的是在函数和所有进程(两个函数都创建进程)完成之后,将一些东西写到文件末尾。 我试图在主要位置编写fprintf命令,它总是在文件中间的某处写入,所以我认为主要和2个函数并行运行。 我试图用信号量 s = sem_open(s1, o_CREATE, 0666, 0);
这样:在每个函数的结尾,我写了sem_post(s)
和主要我把sem_wait(s); sem_wait(s);
和此后我写了fprintf命令,但它也没有工作。 有没有办法解决这个问题? 谢谢在我的程序中的“fork part”
0
A
回答
1
我认为你正在寻找wait
函数。见this stack overflow question:wait(NULL)
将等待所有的孩子完成等待孩子过程完成(感谢Jonathan Leffler)。在循环中调用wait
以等待所有子进程完成。在写入父进程中的文件之前,请立即使用该函数。
如果您想等待特定进程而不是所有进程,还可以阅读waitpid
函数。
编辑: 或者,您实际上可以跨进程使用信号量,但需要多一点工作。见this stack overflow answer。基本思想是使用sem_open
和O_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);
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.
在你的父进程,调用sem_open
与模式和值参数,使它需要你的权限。在子进程中,请致电sem_open("YOUR_SEMAPHORE_NAME", 0)
以打开该信号灯以供使用。
相关问题
- 1. Part-Rails-API/part-Rails应用程序
- 2. C程序中的fork()
- 3. Haskell中的fork和协程程序
- 4. c程序中的多个fork()
- 5. Shell程序中的fork()和wait()
- 6. XWindow应用程序中的fork()/ exec()
- 7. 在fork/execs程序中使用Devel :: NYTProf
- 8. date = date + part vs. date.concat(part)
- 9. 不存在的进程,fork()
- 10. fork系统调用的应用程序
- 11. fork()的C编程
- 12. 问题用fork()在GTK +程序
- 13. 为什么我的Perl程序在fork之后不会收获子进程?
- 14. 为什么在一个简单的程序中使用fork?
- 15. 在cygwin中使用fork编译程序的问题
- 16. 在Qt4应用程序中使用“fork()”的便携方式?
- 17. Resize Eclipse RCP Part
- 18. 使用fork的C++程序中的非阻塞系统调用
- 19. 为什么在应用程序下载文件时名为.part?
- 20. windows中的fork fork和execvp模拟器
- 21. 在fork之后,我需要在父进程中等待()吗?
- 22. 购买Java part 2
- 23. GIT从我的FORK中删除分支
- 24. UNIX进程:fork()和wait()的
- 25. Unix - 使用fork的进程()
- 26. C进程fork()
- 27. python线程/ fork?
- 28. 如何编译我的part文件夹中的scss文件?
- 29. fork()'ed进程中的IO流
- 30. fork()在进程方面的解释?
使用'fork'不是*并行处理* - 这是不正确的术语。 – t0mm13b