【问题标题】:Reading and writng with named pipes C使用命名管道读取和写入 C
【发布时间】:2016-12-09 13:19:27
【问题描述】:

我正在编写一个程序,它应该无限期地运行并保持变量的值。另外两个程序可以更改变量的值。我使用命名管道来接收变量值并将其发送到外部程序。

这是我的变量管理器代码。

ma​​nager.c:

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>

char a = 'a';

void *editTask(void *dummy)
{
    int fd;
    char* editor = "editor";
    mkfifo(editor, 0666);
    while(1)
    {
        fd = open(editor, O_RDONLY);
        read(fd, &a, 1);
        close(fd);
    }   
}

void *readTask(void *dummy)
{
    int fd;
    char* reader = "reader";
    mkfifo(reader, 0666);
    while(1)
    {
        fd = open(reader, O_WRONLY);
        write(fd,&a,1);
        close(fd);      
    }
}

int main()
{
    pthread_t editor_thread, reader_thread;
    pthread_create(&editor_thread, NULL, editTask, NULL);
    pthread_create(&reader_thread, NULL, readTask, NULL);
    pthread_join (editor_thread, NULL);
    pthread_join (reader_thread, NULL);
    return 0;
}

此程序使用 pthread 分别获取变量的外部值并将变量的当前值传递给外部程序。

能够将值写入变量的程序是:

writer.c:

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

int main(int argc, char** argv)
{
    if(argc != 2)
    {
    printf("Need an argument!\n");
    return 0;
    }           
    int fd;
    char * myfifo = "editor";
    fd = open(myfifo, O_WRONLY);
    write(fd, argv[0], 1);      
    close(fd);

    return 0;
}

能读取当前值的程序是:

reader.c:

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

int main()
{
    int fd;
    char * myfifo = "reader";
    fd = open(myfifo, O_RDONLY);
    char value = 'z';
    read(fd, &value, 1);
    printf("The current value of the variable is:%c\n",value);      
    close(fd);

    return 0;
}

我在我的 Ubuntu 系统中运行这些程序如下:

$ ./manager &
[1] 5226
$ ./writer k
$ ./reader
bash: ./reader: Text file busy

为什么我的系统不允许我运行这个程序?

谢谢。

【问题讨论】:

    标签: c named-pipes


    【解决方案1】:

    您正在尝试同时调用 FIFO 和阅读器程序“阅读器”。

    此外,您没有错误检查。您不知道对mkfifoopen 的调用是否成功。在您尝试进行任何故障排除之前,添加此项至关重要。

    【讨论】:

    • 我的错。我四处寻找,但找不到这个错误。我认为当进程尝试并行读取和写入管道时,某处可能存在限制。而关于错误检查,什么样的错误检查是至关重要的?我的意思是,几乎所有功能都可以检查错误,我不能真正为它们烦恼。并感谢您提供有关错误检查的提示。我会记住这一点的。
    • @user5393678 任何有可能失败的函数都应该通过错误检查来调用。这几乎就是所有这些。显然,它是openmkfiforeadwrite,因为它们总是以各种方式失败。而且它几乎没有麻烦,它是if/perror 的简单剪切和粘贴(或使用宏)。老实说,在不知道程序哪里出了问题的情况下,蒙着眼睛尝试排除故障是否更麻烦?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多