2

I am trying to plot data related to CPU usage and memory usage in real time on graph. I am reading data using a c code and transferring it to python script using pipes. Now I want to be able to execute the python script directly from the C program as I am trying to make a console application in C. However my program gets stuck at the statement where I run the python script because the script is then waiting for C code to open the pipe from the other end in write mode. Kindly suggest a way to get past this issue. As no matter from which end I try to access the pipe the code gets stuck waiting for the other program to open it in read/write mode.

Note: the use of both languages is mandatory in my case so the structure of program will remain the same that is C will write data to pipe and python will read it to plot on graph

int writepipe(long long a,char pipename[])
{
    int fd;
    //0777 means this file can be read and be edited by anyone
    if(mkfifo(pipename, 0777)==-1) //returns -1 when an error occurs
    {
        if(errno != EEXIST)
        {
            printf("Could not create FIFO file.\n");
            return -1;
        }
    }
    
    if(strcmp(pipename,"pipe/cpu_pipe")==0)
    {
        system("python3 cpu_graph.py");
    }
    else
    {
        system("python3 mem_graph.py");

    }


    printf("Opening...\n");
    fd = open(pipename, O_WRONLY);
    printf("Opened\n");
    char b[2];
    sprintf(b,"%lld",a);
    char *x;
    x=b;
    


    //printf("Writing...\n");
    if(write(fd, x, sizeof(b)) == -1)
    {
        printf("Write error\n");
        return 1;
    }
    
    close(fd);
    
}
  • 1
    In the `c` program, how about (e.g.) `int fd = popen("python3 cpu_graph.py","w"); while (...) { write(fd,data,sizeof(data)); } close(fd);` – Craig Estey Jan 10 '21 at 20:20
  • `char b[2]; sprintf(b,"%lld",a)` I hope `a` is positive and lower then 10. – KamilCuk Jan 10 '21 at 20:21
  • Does this answer your question? [How to use popen?](https://stackoverflow.com/questions/30259086/how-to-use-popen). There are tons of similar questions. – user14063792468 Jan 10 '21 at 20:23

0 Answers0