2011-10-23 45 views
4

我有以下代碼草稿。如何將fork()後的命令行參數傳遞給子進程

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

int main(int argc, char *argv[]) 
{ 

    printf("usage: %i filename", argc); 

    pid_t pID = fork(); 
    if (pID == 0)    // child 
    { 
     // Code only executed by child process 
     printf("Child PID: %i", pID); 

     int file = open("/tmp/rtail", O_CREAT | O_WRONLY); 

     //Now we redirect standard output to the file using dup2 
     dup2(file,1); 

     char tmp[30]; 
     sprintf(tmp, "cat `tail -f %s`", argv[1]); 
    } 
    else if (pID < 0)   // failed to fork 
    { 
     printf("Failed to fork"); 
     exit(1); 
     // Throw exception 
    } 
    else         // parent 
    { 

    } 

    // Code executed by both parent and child. 

    return 0; 
} 

如何將命令行參數傳遞給子進程?例如,運行./app alch.txt我想

sprintf(tmp, "cat `tail -f %s`", argv[1]); 

生產

cat `tail -f alch.txt` 
tmp中

+3

完全像你這樣做?你的代碼很好。你遇到的問題究竟是什麼? –

回答

7

如何將命令行參數傳遞給子進程?

你不需要做任何特別的事情; fork可確保每個進程獲得所有本地變量,包括argv

1

對不起,它確實工作正常。我之前的版本由於某種原因不起作用,但顯然我已經改變了一些東西以使其正確。下次會在問題出現之前運行我的代碼。

相關問題