繁体   English   中英

使用命名管道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;
}

该程序使用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

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

谢谢。

您正在尝试将FIFO和读取器程序称为“读取器”。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM