user5393678
user5393678

Reputation: 31

Reading and writng with named pipes C

I'm writing a program that should run indefinitely maintaining the value of a variable. Two other programs could change the value of the variable. I use named pipes to receive and send the variable value to external programs.

Here is my code for the manager of the variable.

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

This program uses pthreads to separately get external values for the variable and to communicate the current value of the variable to external programs.

The program that is able to write values to the variable is:

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

The program that could read the current value is:

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

I ran these programs in my Ubuntu system as follows:

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

Why doesn't my system allow me to run this program?

Thank you.

Upvotes: 0

Views: 71

Answers (1)

David Schwartz
David Schwartz

Reputation: 182847

You are trying to call both the FIFO and the reader program "reader".

Also, you have no error checking. You have no idea whether those calls to mkfifo and open succeeded or not. Adding this is critical before you attempt to do any troubleshooting.

Upvotes: 2

Related Questions