【问题标题】:Posix semaphores with FIFO not working properly带有 FIFO 的 Posix 信号量无法正常工作
【发布时间】:2018-11-09 16:41:06
【问题描述】:

我编写了一个小型客户端-服务器演示程序,它应该使用 FIFO 和两个信号量实现两个进程之间的简单通信。 问题是,即使我在客户端读取 fifo 之前放置了 sem_wait,他也不会等待服务器在 fifo 上写入,因此客户端会读取旧值(“2”而不是“pippo”)。我真的找不到错误在哪里。遵循服务器和客户端的代码。 我希望有人可以帮助我。

客户:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <sys/stat.h>   
#include <sys/types.h>
#include <signal.h>
#include <stdarg.h>
#include <fcntl.h>
#define FIFO_FILE "MIA_FIFO"

FILE * fiforw ; 

int fifo_write ( char * buf );  
int fifo_read ( char * buf );

sem_t *pizz;
sem_t *cli;

int main(void){

fiforw=fopen ( FIFO_FILE, "rw");

pizz=sem_open("pizz",  O_EXCL, S_IRUSR | S_IWUSR, 0);
cli=sem_open("cli",  O_EXCL, S_IRUSR | S_IWUSR, 0);

char buff[20];
int pieces=10;;

sprintf(buff,"%d",pieces);

fifo_write(buff);

sem_post(cli);

sem_wait(pizz);

fifo_read(buff);

printf("I've read %s \n",buff);  //here he should read "pippo" instead of "2"


fclose ( fiforw );

}

int fifo_write ( char * buf ) {

    fputs ( buf, fiforw );

    return 1;
}

int fifo_read ( char * buf ) {

    fgets( buf, sizeof(buf)+1, fiforw);

    return 1;
}

服务器:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <sys/stat.h>   
#include <sys/types.h>
#include <signal.h>
#include <stdarg.h>
#include <fcntl.h>
#define FIFO_FILE "MIA_FIFO"

int fifo_write ( char * buf );  
int fifo_read ( char * buf );

sem_t *pizz;
sem_t *cli;
FILE * fiforw;

int main(void){

    mkfifo(FIFO_FILE,0666);
    fiforw = fopen ( FIFO_FILE, "rw");  

    char buff[20];
    char temp[]="pippo";
    pizz = sem_open("pizz", O_CREAT, S_IRUSR | S_IWUSR, 0);
    cli= sem_open("cli", O_CREAT, S_IRUSR | S_IWUSR, 0);

    //while(1) {

    sem_wait(cli);

    fifo_read(buff);

    printf("the value is %s \n",buff);  

    sprintf(buff,"%s",temp);    

    printf("i will write pippo on the fifo \n");

    fifo_write(buff);

    sem_post(pizz);

    fclose ( fiforw );
    //}

}


int fifo_write ( char * buf ) {
    fputs ( buf, fiforw );
    return 1;
}

int fifo_read ( char * buf ) {
    fgets( buf, sizeof(buf)+1, fiforw);
    return 1;
}

【问题讨论】:

  • 首先添加错误检查和处理 - 如果sem_open() 或其他函数失败会发生什么?
  • 您正试图以读写模式打开一个fifo?这……很有趣,因为它们是单向管道。我什至不知道那会是什么样子。
  • 显然这就是问题所在。但是打开它: fiforw=open(fifo_file,O_RDWR) 完美无缺。为什么?

标签: c linux posix fifo


【解决方案1】:

需要先运行服务器,然后是客户端。如果是这种情况,检查系统调用的返回码会很有帮助。

【讨论】:

  • 是的,我已经这样做了。当服务器在 fifo 上写入时程序崩溃。但是如果我用 open(FIFO_FILE,O_RDWR) 打开 fifo,它就可以工作
猜你喜欢
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多