該項目的目標是使用管道和叉執行已經寫入多進程方式的線計數實用程序(每一個參數處理)。我目前正致力於在擴展處理多個參數之前讓單個進程工作。管道和叉
給定兩個可執行文件,lc1
和lc2
,我想lc2
建立一個管道的lc1
標準輸出文件描述符,這樣當execlp("lc1", argv[1], NULL)
被調用時,輸出將被
while ((c= read(pipefd[0], readin, SIZE)) > 0)
根據閱讀我的Unix的書,我應該用開放的,DUP2,close方法重定向標準輸出到標準輸入,這裏是我的代碼:
int pid, c, i;
char *readin= (char *)malloc(sizeof(SIZE));
if (pipe(pipefd)== -1)
perror("Can't open a pipe\n");
for (i=1; i< argc; i++){
if ((pid= fork())==-1)
perror("Can't fork\n");
run(argv[i]);
}
//close pipe
close(1);
if (dup2(pipefd[0], 0)==-1)
perror("Can't redirect stdin");
close(pipefd[1]);
for (i=1; i< argc; i++){
if ((wait(NULL))== -1)
perror("Wait error");
while ((c= read(pipefd[0], readin, SIZE)) > 0){;
//print buf count
total += atoi(readin);
}
}
run函數是
void run(char *f){
int fp;
if ((fp= open(f, O_RDONLY)) == -1)
perror("Can't open the file");
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
execlp("ls1", f, NULL);
}
當我嘗試執行此代碼時,出現stdin重定向錯誤,指出文件描述符不正確。爲什麼會發生這種情況,並希望得到解決的任何提示。
你malloc的說法是錯誤的,我認爲你想字符'*閱讀下載=(的char *)malloc的(大小);' – GWW 2011-05-05 17:16:33
在C.見決不投malloc()函數的返回值http://stackoverflow.com/questions/953112/should-i-explicitly-cast-mallocs-return-value/954785#954785。 – unwind 2011-05-05 17:30:30
不是你的直接問題,但你真的指malloc(sizeof(SIZE))嗎?我假設SIZE是一個常量,所以你分配4或8個字節左右。你可以發佈稍微更完整的代碼嗎?正如發佈,這是有點難以遵循。 – Duck 2011-05-05 18:02:32