Search code examples
cprocessposixqnx

Share data between two indexpendent processes in C


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!


Solution

  • 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.