简体   繁体   中英

How to trigger a process from another process in Linux?

I'm developing a C application on Linux. To make things clear, I translated my problem into two simple programs:

  • Prog1: creates a file and runs an infinite loop to read from it
  • Prog2: writes the word "Hello" into the file 10 times

Whenever the word is written into the file, the infinite loop in Prog1 detects it and simply reads it. (Both codes are mentioned at the end).

The problem is: Prog1 actually tries to read the word then sleeps for 1 second before trying to read again. I want Prog1 to read the word "Hello" as soon as it is written in the file (real time) and if possible, I would like to get rid of the infinite while loop in Prog1.

Is there any professional solution for this problem? like a special high priority interrupt to trigger Prog1 from Prog2?

Thanks.

/* Prog1 */
#define FIFO_FILE "MYFIFO"
int main (void)
{
    int fd;
    int read_bytes;
    char buf[6];

    mknod(FIFO_FILE, S_IFIFO|0640,0);

    while(1)
    {
        fd = open(FIFO_FILE, O_RDONLY);

        read_bytes = read(fd, buf, sizeof(buf));
        if(read_bytes == 0)
            break;

        buf[read_bytes] = '\0';

        printf("Received string is : %s \n", buf);

        sleep(1);
    }

    close(fd);

    return 0;
}

/* Prog2 */
#define FIFO_FILE "MYFIFO"
int main (void)
{
    int fd;
    int stringlen;
    int count = 0;
    char buf[6]={'H','e','l','l','o'};

    fd = open(FIFO_FILE, O_CREAT|O_WRONLY);

    while(count <= 10)
    {   
        stringlen = strlen(buf);
        buf[stringlen] = '\0';

        write(fd, buf, strlen(buf));
        printf("Sent String \n");

        count++;

        sleep(1);

    }

    close(fd);

    return 0;
}

What tyou try to do is what the command tail -f do. You can look over its source code to see the professional solution.

On the other hand, you should not use sleep, but poll from the socket library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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