2

How do I share data (struct) between two independent(no fork) processes. What I want to do is basically something like this:

process1:

Server(PID-399341): Waiting for input....

then in another terminal

process2:

Enter server process:

399341

Enter a string:

Hello

finally

process1:

"Hello" has been entered. 

System is QNX/POSIX. What are my options to do this?

Thanks!

Senri
  • 107
  • 1
  • 1
  • 9

1 Answers1

2

It can be easily achieved by using named pipe (FIFO). Just choose the name of the FIFO same as your PID. Here's a working code for server and client.

server.c

    int fd;
    char buf[10], rdbuf[50];

    sprintf(buf,"%d",getpid());

    if(mkfifo(buf,0660) == -1)
            perror("mkfifo");

    printf("Server(PID-%d): Waiting for input..\n",getpid());

    fd = open(buf,O_RDONLY);

    read(fd, rdbuf, 50);

    printf("%s has been entered\n",rdbuf);

    close(fd);

    return 0;

client.c

    int fd;
    char wrbuf[50], buf[10];

    printf("Enter server process: ");
    scanf("%s",buf);
    getchar();

    fd = open(buf,O_WRONLY);

    printf("Enter message\n");

    gets(wrbuf);

    write(fd, wrbuf, strlen(wrbuf)+1);

I think same can be done with message queue and shared mem segment by making the key value same as PID. But I am not sure.

  • Hi, thanks. Always nice to see simple examples. So how does the server know that the buffer has been changed? I'm planning to use this in a infinite while loop where the client keeps feeding the server messages. – Senri Oct 13 '16 at 14:38
  • Server will always read 50 characters in this example. If there is a null character in there., printf only print that that much. So the buffer is always cleared by server and then it waits for another message, this is taken care by your OS. To be in safe side, put all null characters in buffer before writing to it. – Imtiyaz Shaikh Oct 29 '16 at 12:27
  • I know this is old, as a suggestion for future answers though I recommend adding the includes necessary. In this case we need to include stdio.h, fcntl.h and unistd.h. – mgrenier Mar 10 '23 at 15:16