[英]How can I use pipes to send a flag to a child process?
我需要編寫一個程序來請求 integer,將輸入通過管道傳輸到子進程,在子進程中設置正方形,再通過管道返回父進程,然后請求另一個輸入。
我可以在沒有循環的情況下做到這一點,但是我一輩子都無法弄清楚我需要調用 fork() 和 read() 的順序。
這是我所擁有的:
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void){
int psocket[2];
int csocket[2];
int csig[2];
int sig = 0;
pid_t child;
if(read(csig[0], &sig, sizeof(int)) == -1)
perror("reading signal");
if(sig){
int square;
if(read(csocket[0], &square, sizeof(int))==-1)
perror("read to child");
square = square * square;
if(write(psocket[1], &square, sizeof(int))==-1)
perror("write to parent");
return 0;
}
while(1){
int value;
sig = 1;
printf(">> ");
scanf("%d", &value);
if(value ==0)
break;
if(write(csocket[1], &value, sizeof(int))==-1)
perror("write to child");
if(write(csig[1], &value, sizeof(int))==-1)
perror("write to signal");
child = fork();
wait(NULL);
if(read(psocket[0], &value, sizeof(int))==-1)
perror("read to parent");
printf("\n>> %d\n", value);
}
return 0;
}
但我在嘗試讀/寫 csig pipe 時遇到錯誤
reading signal: Bad file descriptor
>> 32 //entering a value to test
write to signal: Bad file descriptor
在這一點上,我完全迷失了。 go 還有另一種方法嗎? 有什么明顯的我做錯了嗎?
編輯:
我意識到我忘了打電話給 pipe()
我添加了
if ((pipe(psocket) < 0) || (pipe(csocket) < 0) || (pipe(csig) < 0)) {
perror("opening stream socket pair");
exit(10);
}
變量初始化后,現在程序掛起。
我意識到我可以遞歸調用 main() 進程,問題解決了
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void){
int psocket[2];
int csocket[2];
pid_t child;
if(pipe(psocket) < 0 || pipe(csocket) < 0)
perror("pipe");
child = fork();
if(child < 0)
perror("fork");
if(child == 0){
int value = 0;
if(read(csocket[0], &value, sizeof(int)) < 0)
perror("read child");
value = value * value;
if(write(psocket[1], &value, sizeof(int)) < 0)
perror("write parent");
}
else if (child){
int value = 0;
printf(">> ");
scanf("%d", &value);
if(write(csocket[1], &value, sizeof(int)) < 0)
perror("write child");
wait(NULL);
if(read(psocket[0], &value, sizeof(int)) < 0)
perror("read parent");
printf("Squared: %d\n", value);
main();
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.