2016-02-13 90 views
-1

我們應該使用在課堂上提供給我們的代碼來了解叉的工作方式以及我們在不同輸入中看到的差異。我唯一的問題是,當我嘗試運行代碼時,我收到語法錯誤,所以我不確定自己做錯了什麼。任何幫助或指導,非常感謝。語法錯誤testfork C代碼

編輯:忘了澄清我是如何運行這個。學校有一臺我連接到的UNIX機器來運行它。編譯它只是一個問題,其文件名運行它之後是testfork.c

錯誤輸出:

./testfork.c: line 6: syntax error near unexpected token `(' 
./testfork.c: line 6: `int main(int argc, char *argv[])' 

碼塊:

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

int main(int argc, char *argv[]) 
{ 
    pid_t childpid; int count; 

    if (argc < 2) { 
     printf("usage: testfork count\n"); 
     return -1; 
    } 
    else count = atoi(argv[1]); 

    childpid = fork(); 

    if (childpid == -1) { 
     printf("Error in fork; program terminated\n"); 
     return -1; 
    } 

    if (childpid != 0) { 
     /*Code executed by parent process*/ 
     int i; 

     /*The lines below will avoid output interleaving*/ 
     /*int status;*/ 
     /*wait(&status);*/ 

     for (i = 0; i < count; i++) 
     printf("parent process\n"); 
    } 
    else { 
     /*Code executed by child process*/ 
     int j; 
     for (j = 0; j < count; j++) 
     printf("      CHILD PROCESS\n"); 
    } 
    return 0; 
} 
+0

你是如何試圖運行該程序中的任何語法錯誤? – jwodder

+0

我假設你使用'sh'來運行它,對嗎? –

回答

1

代碼似乎是正確的(我只談這裏的語法),並且我可以在我的電腦上完美地編譯和運行它。所以這個問題可能來自你編譯/運行文件的方式。這是一個.c文件,因此您可能需要使用gcc編譯器,例如:

gcc your_file.c -o your_exe -Wall -Wextra-Wall -Wextra是選項,但這總是一個好習慣)。

然後你會發現一個名爲your_exe的新文件,你可以像這樣執行./your_exe(假設你在一臺Linux機器上)。

希望這會有所幫助!

0

只是嘗試這樣做

sh-4.3$ gcc -o testforkx testfork.c                                           
sh-4.3$ ls                                                  
testfork.c testforkx                                               
sh-4.3$ ./testforkx 12 

這裏是輸出我得到:

parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
parent process 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 
        CHILD PROCESS 

沒看到