#include "sys/types.h" #include "sys/file.h" #include "unistd.h" char r_buf[4]; //读缓冲 char w_buf[4]; //写缓冲 int pipe_fd[2]; pid_t pid1, pid2, pid3, pid4; int producer(int id); int consumer(int id); int main(int argc,char **argv){ if(pipe(pipe_fd)<0){//传输出错 printf("pipe create error \n"); exit(-1); } else{ printf("pipe is created successfully!\n"); //谁占用管道谁进行数据传输 if((pid1=fork())==0) producer(1); if((pid2=fork())==0) producer(2); if((pid3=fork())==0) consumer(1); if((pid4=fork())==0) consumer(2); } close(pipe_fd[0]); //需要加上这两句 close(pipe_fd[1]); //否者会有读者或者写者永远等待 int i,pid,status; for(i=0;i<4;i++) pid=wait(&status); //返回子进程状态 exit(0); } //生产者 int producer(int id){ printf("producer %d is running!\n",id); close(pipe_fd[0]); int i=0; for(i=1;i<10;i++){ sleep(3); if(id==1) //生产者1 strcpy(w_buf,"aaa\0"); else //生产者2 strcpy(w_buf,"bbb\0"); if(write(pipe_fd[1],w_buf,4)==-1) printf("write to pipe error\n"); } close(pipe_fd[1]); printf("producer %d is over!\n",id); exit(id); } //消费者 int consumer(int id){ close(pipe_fd[1]); printf(" producer %d is running!\n",id); if (id==1) //消费者1 strcpy(w_buf,"ccc\0"); else //消费者2 strcpy(w_buf,"ddd\0"); while(1){ sleep(1); strcpy(r_buf,"eee\0"); if(read(pipe_fd[0],r_buf,4)==0) break; printf("consumer %d get %s, while the w_buf is %s\n",id,r_buf,w_buf); } close(pipe_fd[0]); printf("consumer %d is over!\n", id); exit(id); }3.参考代码producer()和consumer()中的sleep的作用

时间: 2023-07-14 09:14:24 浏览: 38
在这个代码中,生产者和消费者都使用了 sleep 函数来模拟一些实际情况下需要等待的操作。具体来说,生产者在每次循环中会等待 3 秒钟,以模拟生产过程中的一些耗时操作。而消费者则是在每次循环中等待 1 秒钟,以模拟消费者执行某些操作需要的时间。这样做可以更加接近实际情况,也能够更好地展示管道的使用方式。
相关问题

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #include <grp.h> #include <time.h> void shell_ls_l(char *file,struct stat st) { char limi

ted[11]; // 文件权限 mode_t mode = st.st_mode; limitted[0] = (S_ISDIR(mode)) ? "d" : "-"; limitted[1] = (mode & S_IRUSR) ? "r" : "-"; limitted[2] = (mode & S_IWUSR) ? "w" : "-"; limitted[3] = (mode & S_IXUSR) ? "x" : "-"; limitted[4] = (mode & S_IRGRP) ? "r" : "-"; limitted[5] = (mode & S_IWGRP) ? "w" : "-"; limitted[6] = (mode & S_IXGRP) ? "x" : "-"; limitted[7] = (mode & S_IROTH) ? "r" : "-"; limitted[8] = (mode & S_IWOTH) ? "w" : "-"; limitted[9] = (mode & S_IXOTH) ? "x" : "-"; limitted[10] = '\0'; printf("%s ", limitted); // 链接数、所有者、所在组、文件大小、创建时间、文件名 printf("%ld ", (long)st.st_nlink); printf("%s ", getpwuid(st.st_uid)->pw_name); printf("%s ", getgrgid(st.st_gid)->gr_name); printf("%lld ", (long long)st.st_size); char time_buf[20]; strftime(time_buf, 20, "%b %d %H:%M", localtime(&st.st_ctime)); printf("%s ", time_buf); printf("%s\n", file); } int main(int argc, char *argv[]) { DIR *dir; struct dirent *ptr; struct stat st; char path[256]; if (argc == 1) { getcwd(path, 256); dir = opendir(path); while ((ptr = readdir(dir)) != NULL) { if (ptr->d_name[0] == '.') continue; stat(ptr->d_name, &st); shell_ls_l(ptr->d_name, st); } } else if (argc == 2) { if (strcmp(argv[1], "-l") == 0) { getcwd(path, 256); dir = opendir(path); while ((ptr = readdir(dir)) != NULL) { if (ptr->d_name[0] == '.') continue; stat(ptr->d_name, &st); shell_ls_l(ptr->d_name, st); } } else { dir = opendir(argv[1]); while ((ptr = readdir(dir)) != NULL) { if (ptr->d_name[0] == '.') continue; sprintf(path, "%s/%s", argv[1], ptr->d_name); stat(path, &st); shell_ls_l(ptr->d_name, st); } } } else if (argc == 3) { if (strcmp(argv[1], "-l") == 0) { dir = opendir(argv[2]); while ((ptr = readdir(dir)) != NULL) { if (ptr->d_name[0] == '.') continue; sprintf(path, "%s/%s", argv[2], ptr->d_name); stat(path, &st); shell_ls_l(ptr->d_name, st); } } } return 0; } 这是一个简单的实现Linux命令ls -l的程序,可以列出文件的权限、链接数、所有者、所在组、文件大小、创建时间、文件名等信息。

基于以下代码,分析_exit()与exit()在进程退出时的不同行为,结合行缓冲机制,如果调用_exit()函数结束进程并打印父进程信息,应该怎样操作:#include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> int global=22; char buf[]="the test content!\n"; int mai

n() { int var=88; pid_t pid; int fd; if ((fd=open("testfile",O_CREAT|O_WRONLY|O_TRUNC,0644)) <0) { perror("open error"); exit(1); } if (write(fd,buf,sizeof(buf)-1) != sizeof(buf)-1) { perror("write error"); exit(1); } printf("before fork\n"); if ((pid=fork())<0) { perror("fork error"); exit(1); } else if (pid==0) { global++; var++; printf("child changed\n"); printf("global=%d, var=%d\n",global,var); // exit(0); _exit(0); } if (waitpid(pid,NULL,0)<0) { perror("waitpid error"); exit(1); } printf("parent changed\n"); printf("global=%d, var=%d\n",global,var); exit(0); } 1. _exit()与exit()的区别在于_exit()是直接终止进程,而exit()则是先执行一些清理工作(如调用函数库中的清理函数),然后再终止进程。 2. 在本代码中,如果使用_exit()函数结束进程并打印父进程信息,应该在子进程中添加以下代码: ``` printf("parent process id=%d\n", getppid()); _exit(0); ``` 这样子进程就会直接终止,同时打印出父进程的进程ID。如果使用exit()函数,则需要在子进程中添加清理函数并调用exit()函数来结束进程。

相关推荐

例 2:命名管道通信实例 分别编写读写进程的程序 write.c 和 read.c,两个程序之一在当前目录下创建一个 命名管道“mypipe”,然后 write 向管道写数据,read 从管道读数据,两个进程可 任意顺序运行。 编写 write.c: //write.c #include<stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <error.h> #include <fcntl.h> #include <unistd.h> #define N 256 int main(){ char buf[N]; int fd= open("./mypipe",O_WRONLY|O_CREAT,0666); if(fd!=-1) { printf("FIFO file is opened\n"); } else { perror("open failed"); exit(0); } printf("please input string\n"); scanf("%s",buf); getchar(); if ( write(fd,buf,sizeof(buf))!=-1 ) printf("write successful\n"); else perror("write failed:"); exit(EXIT_SUCCESS); } 编写 read.c: //read.c #include<stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <error.h> #include <fcntl.h> #include <unistd.h> #define N 256 int main(){ int fd= open("./mypipe",O_RDONLY|O_CREAT,0666); char buf[N]; if(fd!=-1) { printf("FIFO file is opened\n"); } else { perror("open failed"); exit(0); } if ( read(fd,buf,N )!=-1 ) printf("I received data %s\n",buf); else perror("read error:"); exit(EXIT_SUCCESS); } 运行方式:打开 2 个终端,分别运行读写进程。 请完成以下练习与回答问题: 练习 1:改写本例,使得写进程可以不断的向管道文件写,读进程可以不断的读, 思考如何控制读写顺序。 练习 2:本例中用于管道通信的是一个普通文件,请用 mkfifo 命令或 mkfifo( )函 数创建一个标准管道文件改写本例,查看一下通过管道文件不断读写有什么不同? 问题 1:请说明匿名管道与命名管道在创建方式上有何不同?为什么说匿名管道 只能用于有亲缘关系的进程间进行通信?

#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include "scull.h" void write_proc(void); void read_proc(void); int main(int argc, char **argv){ if(argc == 1){ puts( "Usage: scull_test [write|read]"); exit(0); } if( !strcmp(argv[1],"write")) write_proc(); else if(!strcmp(argv[1],"read")) read_proc(); else puts( "scull_test: invalid command! "); return 0; } void write_proc(){ int fd, len,quit = 0; char buf[ 100]; fd = open(DEVICE_FILE,O_WRONLY); if(fd <= 0){ printf("Error opening device file %s for writing!\n",DEVICE_FILE); exit(1); } printf( "input 'exit' to exit!"); while( !quit) { printf( "\n write>> "); fgets(buf, 100,stdin); if(!strcmp(buf, "exit\n")) quit =1; while(ioctl(fd,SCULL_QUERY_NEW_MSG)) usleep(1000); len=write(fd, buf, strlen(buf)); if(len<0){ printf( "Error writing to device %s !\n" ,SCULL_NAME); close(fd); exit(1); } printf("%d bytes written to device %s!\n",len- 1,SCULL_NAME); } close(fd); } void read_proc(){ printf("\n read<< "); while(!ioctl(fd,SCULL_QUERY_NEW_MSG)) usleep(1000);// get the msg length len=ioctl(fd, SCULL_QUERY_MSG_LENGTH, NULL); if(len){ if(buf!=NULL) free(buf); buf = malloc(sizeof(char)*(len+1)); len = read(fd, buf, len); if(len < 0){ printf("Error reading from device %s!", SCULL_NAME); }else{ if(!strcmp(buf,"exit\n")){ ioctl(fd, SCULL_RESET); // reset quit = 1; printf("%s\n",buf); }else printf("%s\n",buf); } } free(buf); close(fd); }

#include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <signal.h> //下一步时间间隔 #define TIME_NEXT 50 //定义信号,此处直接使用系统信号,项目中可根据需要自定义信号值#define SIG_UI_QUIT35 #define SIG_PHONE_QUIT 36 #define SIG_UI_QUIT 35 //定义通话状态 enum TASK_PHONE_STATE { TASK_PHONE_STATE_NONE = 0, TASK_PHONE_STATE_RING, TASK_PHONE_STATE_TALK, TASK_PHONE_STATE_HANGUP, }; int phone_state = TASK_PHONE_STATE_NONE; //设置通话状态 void set_state(int state) { phone_state = state; } //获取通话状态 int get_state(void) { return phone_state; } int get_ui_pid() { int pid = -1; FILE *fp = NULL; char buf[12] = {0}; //打开管道,执行 shell 命令查找进程名为task_ui_sig 的pid fp = popen("ps -e I grep \'task_ui_sig\' | awk \'{print $1}\'", "r"); fgets(buf, sizeof(buf), fp); if (strlen(buf) > 0) { pid = atoi(buf); } return pid; } //信号处理函数 void sig_deal(int sig) { if (sig == SIG_UI_QUIT) { printf("Task ui hangup!\n"); set_state(TASK_PHONE_STATE_HANGUP); } } int main(void) { int time = 0; //设置SIG UI QUIT信号处理函数 signal(SIG_UI_QUIT, sig_deal); while (1) { /*模拟与其他用户处理通信协议,每隔5s进入下一状态*/ time++; if (time >= TIME_NEXT) { time = 0; if (get_state() == TASK_PHONE_STATE_RING) { set_state(TASK_PHONE_STATE_TALK); } else if (get_state() == TASK_PHONE_STATE_TALK) { set_state(TASK_PHONE_STATE_HANGUP); } else { set_state(TASK_PHONE_STATE_RING); } printf("Current state is %d!\n", get_state()); /*若当前通话状态为挂断,则退出任务,并发送信号给UI*/ if (get_state() == TASK_PHONE_STATE_HANGUP) { if (get_ui_pid() > 0) { kill(get_ui_pid(), SIG_UI_QUIT); printf("Send quit msg!\n"); } break; } usleep(100 * 1000); } return 0; } }这段代码有什么bug

根据以下代码内容进行补充:#include<semaphore.h> #include #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> sem_t semB,semA;//创建两个信号量 int p=0; int fd=0; //A void * AthreadFunction(void * arg) { int retvalue; unsigned char buf=1; while(1) { sem_wait(&semA);//等待信号量发送 retvalue = write(fd, &buf, sizeof(unsigned char)); if(retvalue < 0){ printf("LED Control Failed!\r\n"); close(fd); return ; } // 请自行添加点亮 LED 函数 printf("LED ON+++++\r\n"); sleep(5); sem_post(&semB);//发送信号量 } } //B void * BthreadFunction(void * arg) { int retvalue; unsigned char buf=0; while(1) { sem_wait(&semB); retvalue = write(fd, &buf, sizeof(unsigned char)); if(retvalue < 0){ printf("LED Control Failed!\r\n"); close(fd); return; } // 请自行添加 LED 关闭函数 printf("LED OFF-----\r\n"); sleep(5); sem_post(&semA); } } int main() { pthread_t pid[2]; int retvalue; char *filename="/dev/led"; /* 打开 led 驱动 */ fd = open(filename, O_RDWR); if(fd < 0){ printf("file %s open failed!\r\n", filename); return -1; } sem_init(&semB,0,0);//初始化信号量 sem_init(&semA,0,0); sem_post(&semA);//先发送一个指定的信号量,不然两个线程会阻塞的等待信号量的 到来 pthread_create(&pid[0],NULL,AthreadFunction,NULL);//创建线程pthread_create(&pid[1],NULL,BthreadFunction,NULL); pthread_join(pid[0],NULL);//线程的回收,避免僵尸线程pthread_join(pid[1],NULL); sem_destroy(&semB);//使用结束后要把信号量给回收 sem_destroy(&semA); retvalue = close(fd); /* 关闭文件 */ // 材料 LED 循环闪烁 10 次后打印自己的姓名+学号,将打印信息截图作为实验报告的支撑 if(retvalue < 0){ printf("file %s close failed!\r\n", filename); return -1; } return 0; }

最新推荐

recommend-type

CCD式铆合测定机保养说明书.doc

CCD式铆合测定机保养说明书
recommend-type

IOS操作系统开发/调试的案例

IOS操作系统开发/调试的案例 iOS操作系统开发和调试是一个复杂但非常有趣的过程。下面是一个简单的iOS应用开发案例,展示了如何使用Swift和Xcode开发一个基本的iOS应用,并进行调试。
recommend-type

【精美排版】基于STCC单片机的简易电子琴.doc

单片机
recommend-type

【精品】毕业设计:单片机模拟交通灯设计.doc

单片机
recommend-type

ATM系统需求说明书.doc

ATM系统需求说明书
recommend-type

数据结构课程设计:模块化比较多种排序算法

本篇文档是关于数据结构课程设计中的一个项目,名为“排序算法比较”。学生针对专业班级的课程作业,选择对不同排序算法进行比较和实现。以下是主要内容的详细解析: 1. **设计题目**:该课程设计的核心任务是研究和实现几种常见的排序算法,如直接插入排序和冒泡排序,并通过模块化编程的方法来组织代码,提高代码的可读性和复用性。 2. **运行环境**:学生在Windows操作系统下,利用Microsoft Visual C++ 6.0开发环境进行编程。这表明他们将利用C语言进行算法设计,并且这个环境支持高效的性能测试和调试。 3. **算法设计思想**:采用模块化编程策略,将排序算法拆分为独立的子程序,比如`direct`和`bubble_sort`,分别处理直接插入排序和冒泡排序。每个子程序根据特定的数据结构和算法逻辑进行实现。整体上,算法设计强调的是功能的分块和预想功能的顺序组合。 4. **流程图**:文档包含流程图,可能展示了程序设计的步骤、数据流以及各部分之间的交互,有助于理解算法执行的逻辑路径。 5. **算法设计分析**:模块化设计使得程序结构清晰,每个子程序仅在被调用时运行,节省了系统资源,提高了效率。此外,这种设计方法增强了程序的扩展性,方便后续的修改和维护。 6. **源代码示例**:提供了两个排序函数的代码片段,一个是`direct`函数实现直接插入排序,另一个是`bubble_sort`函数实现冒泡排序。这些函数的实现展示了如何根据算法原理操作数组元素,如交换元素位置或寻找合适的位置插入。 总结来说,这个课程设计要求学生实际应用数据结构知识,掌握并实现两种基础排序算法,同时通过模块化编程的方式展示算法的实现过程,提升他们的编程技巧和算法理解能力。通过这种方式,学生可以深入理解排序算法的工作原理,同时学会如何优化程序结构,提高程序的性能和可维护性。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

STM32单片机小车智能巡逻车设计与实现:打造智能巡逻车,开启小车新时代

![stm32单片机小车](https://img-blog.csdnimg.cn/direct/c16e9788716a4704af8ec37f1276c4dc.png) # 1. STM32单片机简介及基础** STM32单片机是意法半导体公司推出的基于ARM Cortex-M内核的高性能微控制器系列。它具有低功耗、高性能、丰富的外设资源等特点,广泛应用于工业控制、物联网、汽车电子等领域。 STM32单片机的基础架构包括CPU内核、存储器、外设接口和时钟系统。其中,CPU内核负责执行指令,存储器用于存储程序和数据,外设接口提供与外部设备的连接,时钟系统为单片机提供稳定的时钟信号。 S
recommend-type

devc++如何监视

Dev-C++ 是一个基于 Mingw-w64 的免费 C++ 编程环境,主要用于 Windows 平台。如果你想监视程序的运行情况,比如查看内存使用、CPU 使用率、日志输出等,Dev-C++ 本身并不直接提供监视工具,但它可以在编写代码时结合第三方工具来实现。 1. **Task Manager**:Windows 自带的任务管理器可以用来实时监控进程资源使用,包括 CPU 占用、内存使用等。只需打开任务管理器(Ctrl+Shift+Esc 或右键点击任务栏),然后找到你的程序即可。 2. **Visual Studio** 或 **Code::Blocks**:如果你习惯使用更专业的
recommend-type

哈夫曼树实现文件压缩解压程序分析

"该文档是关于数据结构课程设计的一个项目分析,主要关注使用哈夫曼树实现文件的压缩和解压缩。项目旨在开发一个实用的压缩程序系统,包含两个可执行文件,分别适用于DOS和Windows操作系统。设计目标中强调了软件的性能特点,如高效压缩、二级缓冲技术、大文件支持以及友好的用户界面。此外,文档还概述了程序的主要函数及其功能,包括哈夫曼编码、索引编码和解码等关键操作。" 在数据结构课程设计中,哈夫曼树是一种重要的数据结构,常用于数据压缩。哈夫曼树,也称为最优二叉树,是一种带权重的二叉树,它的构造原则是:树中任一非叶节点的权值等于其左子树和右子树的权值之和,且所有叶节点都在同一层上。在这个文件压缩程序中,哈夫曼树被用来生成针对文件中字符的最优编码,以达到高效的压缩效果。 1. 压缩过程: - 首先,程序统计文件中每个字符出现的频率,构建哈夫曼树。频率高的字符对应较短的编码,反之则对应较长的编码。这样可以使得频繁出现的字符用较少的位来表示,从而降低存储空间。 - 接着,使用哈夫曼编码将原始文件中的字符转换为对应的编码序列,完成压缩。 2. 解压缩过程: - 在解压缩时,程序需要重建哈夫曼树,并根据编码序列还原出原来的字符序列。这涉及到索引编码和解码,通过递归函数如`indexSearch`和`makeIndex`实现。 - 为了提高效率,程序采用了二级缓冲技术,它能减少磁盘I/O次数,提高读写速度。 3. 软件架构: - 项目包含了两个可执行文件,`DosHfm.exe`适用于DOS系统,体积小巧,运行速度快;而`WinHfm.exe`则为Windows环境设计,提供了更友好的图形界面。 - 程序支持最大4GB的文件压缩,这是Fat32文件系统的限制。 4. 性能特点: - 除了基本的压缩和解压缩功能外,软件还提供了一些额外的特性,如显示压缩进度、文件一致性检查等。 - 哈夫曼编码的使用提高了压缩率,而二级缓冲技术使压缩速度提升了75%以上。 这个项目不仅展示了数据结构在实际问题中的应用,还体现了软件工程的实践,包括需求分析、概要设计以及关键算法的实现。通过这样的课程设计,学生可以深入理解数据结构和算法的重要性,并掌握实际编程技能。