-
-
Save hxzhouh/7c201a16f6dc37068fa9eefae9334b04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/time.h> | |
#include <time.h> | |
#include <sched.h> | |
#include <sys/types.h> | |
#include <unistd.h> //pipe() | |
/** | |
* @brief This program demonstrates context switching between two processes using pipes. | |
* | |
* The program creates two pipes, `fd` and `p`, and forks a child process. | |
* The child process reads from `fd[0]` and writes to `p[1]`, while the parent process | |
* writes to `fd[1]` and reads from `p[0]`. This creates a loop where the child and parent | |
* processes alternate sending and receiving characters through the pipes. | |
* | |
* The program also sets the scheduling policy of both processes to `SCHED_FIFO` using | |
* `sched_setscheduler()` function. It measures the time before and after the context | |
* switch using `gettimeofday()` function and prints the results. | |
* | |
* @return 0 on success. | |
*/ | |
int main() | |
{ | |
int x, i, fd[2], p[2]; | |
char send = 's'; | |
char receive; | |
pipe(fd); | |
pipe(p); | |
struct timeval tv; | |
struct sched_param param; | |
param.sched_priority = 0; | |
while ((x = fork()) == -1); | |
if (x==0) { | |
sched_setscheduler(getpid(), SCHED_FIFO, ¶m); | |
gettimeofday(&tv, NULL); | |
printf("Before Context Switch Time%u s, %u us\n", tv.tv_sec, tv.tv_usec); | |
for (i = 0; i < 10000; i++) { | |
read(fd[0], &receive, 1); | |
write(p[1], &send, 1); | |
} | |
exit(0); | |
} | |
else { | |
sched_setscheduler(getpid(), SCHED_FIFO, ¶m); | |
for (i = 0; i < 10000; i++) { | |
write(fd[1], &send, 1); | |
read(p[0], &receive, 1); | |
} | |
gettimeofday(&tv, NULL); | |
printf("After Context SWitch Time%u s, %u us\n", tv.tv_sec, tv.tv_usec); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment