简体   繁体   中英

Linux: FIFO scheduler isn't working as expected

I am currently trying to work with Linux FIFO schedulers.

I want to run two processes: process A and process B with the same priority in a FIFO way. To do this, I have made a shell script in which I run process A first, followed by process B. In FIFO format, process B should start its execution only after the completion of process A, ie, there should be no overlapping between the execution of these processes. But this isn't what is happening. I am actually observing that both of the processes are running in an overlapping fashion, ie, the print statements are printing in both the processes in an interleaved format.

Here is the code of the shell script.

gcc -o process_a process_a.c
gcc -o process_b process_b.c
sudo taskset --cpu-list 0 chrt -f 50 ./process_a &
sleep 0.1
sudo taskset --cpu-list 0 chrt -f 50 ./process_b &
sleep 30
exit

To make sure that both the processes run on the same CPU, I have used taskset command. Also, I am using chrt command to set the scheduler.

Here is the code for process_a.c

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <sched.h>


int main(int argc, char *argv[])
{
    printf("Process A begins!\n");
    fflush(stdout);
    long long int i=0, m = 1e8;
    while(i<2e10){
        if(i%m == 0){
            printf("Process A running\n");
            fflush(stdout);
        }
        i++;
    }
    printf("Process A ended \n");
    fflush(stdout);
  
    return 0;
}

Here is the code for process_b.c

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <sched.h>


int main(int argc, char *argv[])
{
    printf("Process B begins!\n");
    fflush(stdout);
    long long int i=0, m = 1e8;
    while(i<2e10){
        if(i%m == 0){
            printf("Process B running\n");
            fflush(stdout);
        }
        i++;
    }
    printf("Process B ended \n");
    fflush(stdout);
  
    return 0;
}

Please help me understand why this is happening.

Many thanks in advance.

The sched(7) manual page says this:

A SCHED_FIFO thread runs until either it is blocked by an I/O request, it is preempted by a higher priority thread, or it calls sched_yield(2) .

In this case, you're performing an I/O request to the terminal via printf , which calls write under the hood. Your file descriptor is in blocking mode, so it is likely that at least some blocking occurs in this case since generally I/O is slow, especially to terminals, causing the other process to run.

If you wanted a better example of one process preventing the other from running, you'd probably want to do something like write into a shared memory segment instead, which wouldn't be blocked by an I/O request.

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