這是一種無法實現的特殊場景。我想了解我「在做什麼錯誤通過分支進程通過管道傳遞變量來執行Shell命令
情景:
1.叉一個子進程 2.子進程應執行shell命令(例如貓排序文件) 3。外殼命令的參數從父進程通過配管(用於G例如文件輸入。貓排序)
我寫以下程序但它顯示的文件名,而不是打印出文件內容。但它掛着出到屏幕上
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(){
int pipefd[2];
pipe(pipefd);
//create a pipe before you fork a child process
pid_t cpid = fork();
if(cpid < 0){
perror("Fork");
}
else if(cpid == 0){
printf("This is child process\n");
close(pipefd[1]);
close(0);
dup2(pipefd[0],0);
execlp("sort", "sort", NULL);
exit(0);
}
else{
printf("This is parent process\n");
close(pipefd[0]);
char *sort_array[] = {"hello", "amigos", "gracias", "hola"};
for (int i=0; i<4; i++){
write(pipefd[1],sort_array[i],strlen(sort_array[i]));
write(pipefd[1], "\n",1);
}
int cstatus;
wait(&cstatus);
}
}
給予任何輸出更新:
原來的例子是無效的。我更新了排序命令。
我想對內容進行排序。但屏幕掛,沒有任何輸出
這麼傻,我忘了它。真的很糟糕的一天。我花了整整一天的時間去了解描述符關閉:)。非常感謝 – user3151330