#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 08:14:24 浏览: 29
在这个代码中,生产者和消费者都使用了 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

阿里巴巴六个盒子实践.pptx

阿里巴巴六个盒子实践.pptx
recommend-type

Vue JS 和 Firebase 数据库实现的在线购物车系统项目源码(可做毕设项目参考)

项目简介: VueJS 和 Firebase 数据库中的在线购物车系统是一个基于Web的应用程序,旨在提供一个简单而高效的在线购物体验。该项目使用VueJS进行前端开发,并使用Firebase作为数据库来存储和管理购物车数据。通过这个项目,用户可以添加商品到购物车、查看购物车内容、进行结账等操作。 项目目标: 提供一个功能完备的在线购物车系统。 提供用户友好的操作界面。 提高用户的编程技能,特别是VueJS和Firebase的应用能力。 项目功能 添加商品到购物车: 用户可以浏览商品并将其添加到购物车中。 查看购物车内容: 用户可以查看购物车中的所有商品,包括商品名称、数量、价格等信息。 更新购物车: 用户可以更新购物车中的商品数量或删除商品。 结账: 用户可以进行结账操作,完成购买流程。 项目优势 高效的购物体验: 提供便捷的购物车功能,提高用户的购物体验。 用户友好: 界面简洁,操作简单,用户可以轻松使用该应用程序。 提高编程技能: 通过实践项目,提高对VueJS和Firebase的应用能力。 结论 VueJS 和 Firebase 数据库中的在线购物车系统是一个简单且实用的小项目
recommend-type

一个基于PHP的开源轻简论坛

一个基于PHP的开源轻简论坛 服务器环境要求: 支持子目录安装论坛 PHP 5.3+ 包括5.3 , 5.3以上环境 Apache || Nginx || IIS 需要开启伪静态,否则无法安装~! 数据库支持 : MYSQL , MSSQL ,Oracle ,SQLite ,PostgreSQL ,Sybase 等.. PHP支持扩展 需要开启 PDO ##### PDO PDO PDO 否则数据库玩不了 以文件缓存形式运行论坛, 支持自由的 **模板 **与 插件 开发 所以非常适合二次开发,论坛基于框架开发, 很多操作都是非常简单, 论坛也封装了 Model提供使用 所以二次开发并不需要修改论坛源代码, 只需要增加自己的插件 从中修改论坛 用户也可以通过模板机制自己内容来源于网络分享。仅供学习使用。请勿商用。如有侵权,请联系我。我将立即删除开发一套属于自己的模板, 模板拥有框架标签解析引擎, 是非常容易开发的 论坛可承载亿级数据库 运行 0.00x速度, 当然是用了xcache加速编译 , 论坛也在开发测试中. 论坛暂时没开发 数据缓存
recommend-type

pyzmq-15.2.0.zip

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

每日随机素材!!!!!!!!!!!

每日随机素材
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

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

优化MATLAB分段函数绘制:提升效率,绘制更快速

![优化MATLAB分段函数绘制:提升效率,绘制更快速](https://ucc.alicdn.com/pic/developer-ecology/666d2a4198c6409c9694db36397539c1.png?x-oss-process=image/resize,s_500,m_lfit) # 1. MATLAB分段函数绘制概述** 分段函数绘制是一种常用的技术,用于可视化不同区间内具有不同数学表达式的函数。在MATLAB中,分段函数可以通过使用if-else语句或switch-case语句来实现。 **绘制过程** MATLAB分段函数绘制的过程通常包括以下步骤: 1.
recommend-type

SDN如何实现简易防火墙

SDN可以通过控制器来实现简易防火墙。具体步骤如下: 1. 定义防火墙规则:在控制器上定义防火墙规则,例如禁止某些IP地址或端口访问,或者只允许来自特定IP地址或端口的流量通过。 2. 获取流量信息:SDN交换机会将流量信息发送给控制器。控制器可以根据防火墙规则对流量进行过滤。 3. 过滤流量:控制器根据防火墙规则对流量进行过滤,满足规则的流量可以通过,不满足规则的流量则被阻止。 4. 配置交换机:控制器根据防火墙规则配置交换机,只允许通过满足规则的流量,不满足规则的流量则被阻止。 需要注意的是,这种简易防火墙并不能完全保护网络安全,只能起到一定的防护作用,对于更严格的安全要求,需要
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。