2017-04-25 24 views
0

之后执行程序,我在主函数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

使用'fork'不是*并行处理* - 这是不正确的术语。 – t0mm13b

回答

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. 

在你的父进程,调用sem_open与模式和值参数,使它需要你的权限。在子进程中,请致电sem_open("YOUR_SEMAPHORE_NAME", 0)以打开该信号灯以供使用。

+0

可能有助于简要总结每个答案传达的内容,而不是倾销链接。 – t0mm13b

+0

会做,谢谢。 – mgarey

+0

我不确定,但我认为我完全按照您的说法来制作它。我喜欢它: 主: sem_t * s; s = sem_open(s1,O_CREAT,0666,0); sem_close(s); s = sem_open(s1,O_RDWR);功能1和2: sem_t * s; s = sem_open(s1,O_RDWR); “s1”是一个宏。 – Erik