使用命名管道 C 读写

Reading and writng with named pipes C

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

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

manager.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;
}

此程序使用 pthreads 单独获取变量的外部值,并将变量的当前值传递给外部程序。

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

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

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

谢谢。

您正在尝试同时调用 FIFO 和 reader 程序 "reader"。

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