2013-01-02 32 views
-2

我怎樣才能改變,這樣的功能function_delayed_1function_delayed_2只進行一次,並同時計劃:C,流程,叉

int main(int argc, char *argv[]) { 
    printf("message 1.\n"); 
    fork(); 
    function_delayed_1(); 
    function_delayed_2(); 
    printf("message 2.\n"); 
} 
+1

你嘗試過什麼?你在課堂上學到了什麼?你從你讀過的文檔中學到了什麼? –

+1

請閱讀'fork'手冊。 – ydroneaud

回答

2

閱讀man頁面叉的,而谷歌的fork();一些例子,,你的代碼應該像如下:

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

int main(int argc, char *argv[]) { 
    pid_t pid; // process ID 

    printf("message 1.\n"); 
    pid = fork(); 
    if (pid < 0) { 
     perror("fork"); 
     return; 
    } 

    if (pid == 0) { 
     function_delayed_1(); // child process 
    } 
    else { 
     function_delayed_2(); // parent process 
    } 
    printf("message 2.\n"); 
} 
+1

調用fork()時缺少錯誤檢查。即使fork()失敗,也會執行'function_delayed_2()'。 – alk

1
int main(int argc, char *argv[]) { 
    printf("message 1.\n"); // printed once by parent process 
    if(fork()) 
     function_delayed_1(); // executed by parent process 
    else 
     function_delayed_2(); // executed by child process 

    printf("message 2.\n"); // will be printed twice once by parent & once by child. 
} 
+0

-1您忘記了錯誤檢查。 – Johan