2017-04-25 25 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