2012-02-03 38 views
0

好的,我發佈了我的代碼。我解釋了之前我想要做的事情。發佈我的c文件,我希望你能找到我的錯誤。謝謝 這是myfork.c我在調用c文件時如何添加參數

#include <stdio.h> 
#include <unistd.h> 
int main(int argc,char *argv[]) 
{ 
    int pid; 
    int s; 
    int waitPid; 
    int childPid; 

    pid = fork(); 
    if (pid == 0 && pid != -1) { 
    childPid = getpid(); 
    printf("Child Process ID:%d, Parent ID:%d, Process " 
      "Group:%d\n",childPid,getppid(),getgid()); 
    execl("/bin/cat","cat","-b","-t","-v",argv[1],(char*)NULL); 
    } else { 
    printf("Original Process ID:%d, Parent Is:%d, Process Group " 
      "Is:%d\n",childPid,getppid(),getgid()); 
    waitPid = waitpid(childPid,&s,0); 
    } 
    return 1; 
} 

這是test.c的

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

int main(void){ 
    pid_t fork_return; 
    fork_return = fork(); 
    if (fork_return==0) { 
    printf("In the CHILD process\n"); 
    } else { 
    printf("In the PARENT process\n"); 
    } 
    return 0; 
} 
+0

./mywork blahblah – 2012-02-03 02:50:36

+0

嗯,我嘗試過,但它給了這樣的事情: 原始進程ID:0,家長是:11875,進程組:12024 子進程ID:12977,父ID:12976,流程組:12024 和這裏的test.c文件的代碼 Original ID:0我認爲我做錯了什麼 – 2012-02-03 02:57:20

+0

和輸出必須是這樣的:第一個子進程的信息,然後test.c文件的索引並在最後,父母的過程信息(原始過程) – 2012-02-03 03:00:09

回答

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

int main(int argc, char *argv[]) 
{ 
    int pid; 
    int s; 
    int waitPid; 
    int childPid; 

    if ((pid = fork()) == -1) 
    { 
     perror("fork"); 
     exit(1); 
    } 

    if (pid == 0) 
    { 
     printf("Child Process ID:%d, Parent ID:%d, Process Group:%d\n", getpid(), getppid(), getgid()); 

     execl("/bin/cat", "cat", "-b", "-t", "-v", argv[1], (char*)NULL); 
    } 
    else 
    { 
     waitPid = waitpid(pid, &s, 0); 

     printf("Original Process ID:%d, Parent (of parent) Is:%d, Process Group Is:%d\n", getpid(), getppid(), getgid()); 
    } 

    return 0; 
} 

./myfork test.c的

你可能想測試execl()不失敗等等。除了一些非常小的錯誤,你基本上已經擁有了它。最重要的是把之後的父母printf()

+0

非常感謝我的朋友。你解決了我的問題。 – 2012-02-03 03:50:56

2

您似乎希望在等待孩子後打印有關父進程的信息,以便在waitpid之後移動printf語句。在父進程中,childPid的值也是垃圾。您應該改用pid。另外最好分開處理-1。在東西也許這些線路:

pid = fork(); 
if (pid == -1) 
{ 
    perror("fork"); 
    /* Handle error*/ 
} 
else if(pid == 0){ 
    printf("Child Process ID:%d, Parent ID:%d, Process Group:%d\n",getpid(),getppid(),getgid()); 
    execl("/bin/cat","cat","-b","-t","-v",argv[1],(char*)NULL); 
    perror("execl"); /* Print the error message for execl failure*/ 
} 
else{ 
    waitPid = waitpid(pid,&s,0); /* pid holds child's pid in parent process*/ 
    printf("Original Process ID:%d, Parent Is:%d, Process Group Is:%d\n",getpid(),getppid(),getgid()); 
} 

旁註:
1.也許最好使用pid_t而不是intpid & waitPid。你可以擺脫childPid
2.您應該包括sys/types.hpid_t & sys/wait.hwaitpid
3.通常當沒有錯誤時main()返回0
希望這有助於!

+0

你說得對。謝謝。你和Duck都是對的。 – 2012-02-03 03:51:38

相關問題