[英]Fifo [c] Training
出於個人對Fifo和C語言程序開發的興趣,我堅持使用此練習,顯然我犯了大錯誤。 Fifo已創建,但內部沒有流程,必須依靠Fifo的保護/關閉/打開機制。 請幫忙。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char** argv)
{
int c;
int fi;
int fo;
int stat;
int pid;
fprintf(stderr, "Fifo...\n");
if (mkfifo("FifoA", 0666)==-1) {
exit(1);
}
if (mkfifo("FifoB", 0666)==-1) {
exit(1);
}
pid = fork();
switch (pid) {
case 0:
if((fo=open("FifoA",O_RDONLY))==-1)
{
perror("error FifoA");
exit(1);
}
close(fi);
while (read(fo, &c, 1)>0) {
c = toupper(c);
fputc(c,stdout);
}
break;
case -1:
fprintf(stderr, "Fork error\n");
exit(1);
default:
if((fi=open("FifoB",O_WRONLY))==-1)
{
perror("error FifoB");
exit(1);
}
close(fo);
while ((c = fgetc(stdin))!=EOF) {
write(fi, &c, 1);
}
close(fi);
wait(&stat);
break;
}
return 0;
}
在fork()
之后打開fifo,在子O_RDONLY
中使用O_RDONLY
,在父級中使用O_WRONLY
。 這樣,fifo可以知道兩端都已打開,並開始通信。 記住,fifo是單向的, O_RDWR
沒有意義。
您的最后一個問題是您創建了兩個不同的fifo,並希望它們能夠相互交談。
if((fo=open("FifoA",O_RDONLY))==-1)
//...
if((fi=open("FifoB",O_WRONLY))==-1)
應該
if((fo=open("FifoA",O_RDONLY))==-1)
//...
if((fi=open("FifoA",O_WRONLY))==-1)
Fifo有兩個方面。 一個進程從一側寫入,另一進程從另一側讀取。 如果您的唯一目標是讀寫程序,則只需要一個fifo。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.