c - FIFO read() 函数卡在 c 中

标签 c linux pipe named-pipes

我试图从一个进程中读取一个文本文件的字符串,然后通过 LINUX 上的命名管道将该字符串传递给另一个进程。问题是当我在控制台中键入“./reader text.txt = receiver”时,如果我输入以下行,接收过程的 read() 函数将返回错误

fcntl(fd, F_SETFL, O_NONBLOCK);

或者如果我删除它就会卡在 read() 函数上。

这里是读取字符串的过程(reader)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h> 

 int main(int argc,char *argv1[]){

 if(argc==4 && strcmp(argv1[2],"=") == 0){

 char mesaj[99999]; //message to be delivered

    char line[150];
    FILE *fp =fopen(argv1[1],"r");  //reading from a text file

    if(fp==NULL){

        printf("text file error!");
        exit(1);
    }


    while(fgets(line,sizeof(line),fp)){
        strcat(mesaj,line); //append every line to message

    }

    fclose(fp);

    mesaj[strlen(mesaj)-1]='\0';

    int n =strlen(mesaj)+1;


   //printf("got the text  %s\n",mesaj);


    if(mkfifo("myFifo",0777)== -1 && errno!= EEXIST){ 
        printf("Pipe error");
        exit(1);
    }


    printf("opening\n");
    int fd= open("myFifo",O_RDWR);
    if(fd==-1){
        printf("open error");
        exit(1);
    }
    printf("opened");


    if( write(fd, mesaj,sizeof(char)*n)==-1){
        printf("write error");
        exit(1);
    }


    printf("written");

    close(fd);

    printf("closed");
    fflush(stdout);


   char mesajSizeChar[n];
   sprintf(mesajSizeChar, "%d", n);


    char *args[]={mesajSizeChar,NULL}; //send the message size as parameter for the other process
    char program[]="./";
    strcat(program,argv1[3]); // recieved process name as parameter
    execv(program,args); // call the other process
    perror("execv");


    return 0;
     }
 }

这是接收过程(接收者)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc,char *argv1[]){

int mesajSize=atoi(argv1[0]); //convert message size to integer
char mesaj[99999];

printf("\ncame here\n");


int fd= open("myFifo",O_RDWR);
fcntl(fd, F_SETFL, O_NONBLOCK);
printf("\nopen \n");

if(fd==-1)
    printf("pipe error\n");


if(read(fd,mesaj,sizeof(char)*mesajSize)==-1)
printf("read error\n");


printf("read \n");
printf("\nworked: %s \n",mesaj);

close(fd);
return 0;

 }

最佳答案

问题是您在第一个进程中关闭了管道。管道没有任何永久存储,它只能在至少被一个进程打开时保存数据。当您关闭管道时,您写入的数据将被丢弃。

因此,当第二个进程尝试从管道读取时,没有任何可用的。

执行第二个进程时需要保持管道FD打开。去掉阅读器程序中的 close(fd);

关于c - FIFO read() 函数卡在 c 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62351619/

相关文章:

c - fork 和子/父进程

c++ - C语言中函数中的switch指针

c++ - 执行控制台程序,写入标准输入并使用管道读取结果

c - 错误 : redefinition of "a static variable" in C header files

c - 如果0在c程序中编译

python - 如何在 linux 终端控制台中运行 python 脚本并继续使用命令行?

Linux bash 备份脚本 - 12、9、6、3、1 个月

linux - 为什么只有在按回车后才能在串行连接中接收到字符?

linux - 将 stderr 通过管道传输到自动 ftp 脚本中的 syslog

python - 多进程写入python中的一个管道