日期:2014-05-16 浏览次数:20686 次
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sched.h> #include <time.h> #include <sys/time.h> #include <pthread.h> #include <sys/wait.h> int main(int argc, char* argv[]) { int prio_max,data,i,iter_count; int pfd1[2],pfd2[2],time_pipe[2]; pid_t pid,child; struct timeval start,end; struct sched_param prio_param; cpu_set_t cpuset; if( argc > 1 ) iter_count = atoi(argv[1]); else iter_count = 10000; CPU_ZERO(&cpuset); CPU_SET(0,&cpuset); memset(&prio_param,0,sizeof(struct sched_param)); pid = getpid(); if( sched_setaffinity(pid,sizeof(cpu_set_t),&cpuset) < 0 ){ perror("sched_setaffinity"); exit(EXIT_FAILURE); } if( (prio_max = sched_get_priority_max(SCHED_FIFO)) < 0 ){ perror("sched_get_priority_max"); exit(EXIT_FAILURE); } printf("prio_max: %d\n",prio_max); prio_param.sched_priority = prio_max; if( sched_setscheduler(pid,SCHED_FIFO,&prio_param) < 0 ){ perror("sched_setscheduler"); exit(EXIT_FAILURE); } if( pipe(pfd1) < 0 ){ perror("pipe"); exit(EXIT_FAILURE); } if( pipe(pfd2) < 0 ){ perror("pipe"); exit(EXIT_FAILURE); } if( pipe(time_pipe) < 0 ){ perror("pipe"); exit(EXIT_FAILURE); } if( (child = fork()) < 0 ){ perror("fork"); exit(EXIT_FAILURE); }else if( child == 0 ){ int n = sizeof(data); close(pfd1[1]); close(pfd2[0]); close(time_pipe[0]); for( i = 0; i < iter_count; i++ ){ if( read(pfd1[0],&data,sizeof(data)) != n ){ perror("read at child process"); exit(EXIT_FAILURE); } if( write(pfd2[1],&data,sizeof(data)) != n){ perror("write at child process"); exit(EXIT_FAILURE); } } gettimeofday(&end,NULL); n = sizeof(struct timeval); if( write(time_pipe[1],&end,sizeof(struct timeval)) != n ){ perror("write at child process"); exit(EXIT_FAILURE); } close(pfd1[0]); close(pfd2[1]); close(time_pipe[1]); exit(EXIT_SUCCESS); }else{ double switch_time,yield_time; struct timeval yield; int n; close(pfd1[0]