2015-10-19 35 views
0

我試圖獲取程序(父項和子項)每次運行的結果。結果只在屏幕上打印一次,而在文件中只打印一次。我似乎無法得到兩個獨特的文件(一個代表父母,一個代表孩子)。我不確定getpid()是分離父和子標識的有效方法。我可能做錯了什麼?在C中fork()的結果記錄到文件以查看結果

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 

    static char *app1="/path/to/app1"; 
    static char *app; 
    static pid_t forky=-1; 

    void otherfunction(){ 
     int aflag=1; 
     //do something 
     if (aflag==1){ 
     //run app 1 
     app=app1; 
     printf("Starting fork\n"); 
     forky=fork(); 
     } 
    } 

int main(){ 
     char dat[40000],test[10000]; 
     sprintf(dat,"Exec start\nFORKY = %d\nPID = %d\nPPID = %d\n",forky,getpid(),getppid()); 
     sprintf(test,"/TEST%d",getpid()); 
     int h=open(test,O_WRONLY|O_CREAT); 
     write(1,dat,strlen(dat)); 
     write(h,dat,strlen(dat)); 
     close(h); 
     otherfunction(); 
     return 0; 
    } 

回答

1

您在調用fork之前正在創建該文件。叉是最後一件事,然後這兩個進程返回0.

0

按照fork's man page中的說明,通過調用fork創建的進程是父進程的副本,除了一些特定的差異,並且此子進程開始執行彷彿在撥打fork後恢復。所以,這有點像你從fork得到兩個回報,一個給父母,一個給孩子。因此,它看起來就像你在這裏問兩個問題:

如何區分父母和孩子

再次,man page提到叉將返回孩子的父進程PID和0的子過程,從而下面的代碼示例將讓你尊貴的輸出從兩個:

#include <stdio.h> 
#include <unistd.h> 

int main(int argc, char **argv) 
{ 
    pid_t pid = fork(); 

    if (pid == 0) 
     printf("Hello from child!!!\n"); 
    else if(pid > 0) 
     printf("Hello from parent!!!\n"); 
    else 
     printf("Wow, fork failed!!!"); 

    return 0; 
} 

獲得單獨的文件爲每個進程

如上所述,兩個進程從恢復後,調用fork,所以必須在調用fork後創建。在你的例子中,你主要調用otherfunction last,所以fork幾乎是兩個進程中的最後一次調用。

以下是一個示例,它將爲您提供每個進程的不同內容的不同文件,以及每個進程的stdout打印。這裏使用getpid只是讓你可以檢查手冊頁的內容。

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 

int main(int argc, char **argv) 
{ 
    pid_t pid = fork(); 
    int h; 
    char *test; 
    char dat[100]; 

    if (pid == 0) 
     test = "child"; 
    else if(pid > 0) 
     test = "parent"; 
    else 
     test = "failed"; 

    h = open(test,O_WRONLY|O_CREAT); 
    sprintf(dat, "%s | fork returned = %d | my_pid = %d\n", test, pid, getpid()); 
    write(1,dat,strlen(dat)); 
    write(h,dat,strlen(dat)); 
    close(h); 
}