我有,我必須實現一個鍵盤記錄到我們在課堂上做了一個殼的問題。我遇到了麻煩while循環內的程序的流程創建一個子進程後繼續循環,它已經跑了execlp()。Ç - while循環與叉()/管()內
下面是一個簡單的程序,我已經對我有麻煩的部分工作..我的主程序,pipe.c,包括while循環的父/子的過程,「應該」繼續獲得輸入從用於fgets()的用戶,創建子進程,使用DUP2(),寫入stdout,然後子進程調用receive.c的可執行文件,將從標準輸入獲取輸入並顯示它..
/* file: pipe.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int key_logger_on = 0;
int p[2];
pid_t pid;
char str[256];
char input[1024];
int status;
char * file = "test.txt";
printf("Input :: ");
while(fgets(input, sizeof(input), stdin)) {
if (pipe(p)==-1) {
perror("Pipe create error");
exit(1);
}
if ((pid=fork())==-1) {
perror("Fork create error");
exit(1);
}
if (pid==0) {
close(p[1]); // Close write
dup2(p[0],0);
close(p[0]);
execlp("receive",file,NULL);
}
else {
close(p[0]); // Close read
fflush(stdout);
dup2(p[1],1);
close(p[1]);
write(1, input, strlen(input)+1);
waitpid(pid, NULL, 0);
}
printf("Input :: ");
}
}
這裏是簡單的receive.c獲取輸入的stdin並顯示它。該文件只是傳遞參數的測試。
/* file: receive.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
char input[256];
fgets(input, sizeof(input), stdin);
printf("FILE: %s RECEIVE: %s", argv[0],input);
return 0;
}
現在,這一切都做對我來說,當跑的第一次,它得到的輸入,將其發送到標準輸出,兒童電話接收,打印出的輸入,然後整個父程序退出, while循環被忽略,一切都結束了。我對叉子和喉管很陌生,所以這是非常令人沮喪的處理!甚至讓我第一次在這裏發佈一個問題!非常感謝你提前。
嗨,我今天做到了。對我來說也是重複。檢查我的答案 – qwr 2013-05-12 18:27:53