#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) strcpy(w_buf,"aaa\0"); else strcpy(w_buf,"bbb\0"); if(write(pipe_fd[1],w_buf,4)==-1) printf("write to pipe erroe\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) strcpy(w_buf,"ccc\0"); else 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); } 看以上代码,回答以下问题1. 参考代码main中两个close (pipe_ fd[0]) 和close(pipe. fd[1]) 的作用: 3.参考代码中for(i=0;i<4;i++) pid=wait (&ststus) ; 的作用,如果没有会是何种结果,为什么? 3.参考代码producer ()和consumer ()中的sleep的作用:

时间: 2024-01-05 19:05:16 浏览: 26
1. 参考代码中的两个 close(pipe_fd[0]) 和 close(pipe_fd[1]) 的作用是关闭管道的读和写端,以便后续的 wait 函数能够正确结束进程。 2. 参考代码中的 for(i=0;i<4;i++) pid=wait(&status); 的作用是等待所有子进程结束并回收资源,如果没有等待子进程结束,则会导致子进程变成僵尸进程,浪费系统资源。 3. 参考代码中的 sleep 的作用是为了模拟生产者和消费者的实际操作,让进程在一定的时间间隔内进行操作,以便更好地观察程序的运行情况。
相关问题

#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

QT5开发及实例配套源代码.zip

QT5开发及实例配套[源代码],Qt是诺基亚公司的C++可视化开发平台,本书以Qt 5作为平台,每个章节在简单介绍开发环境的基础上,用一个小实例,介绍Qt 5应用程序开发各个方面,然后系统介绍Qt 5应用程序的开发技术,一般均通过实例介绍和讲解内容。最后通过三个大实例,系统介绍Qt 5综合应用开发。光盘中包含本书教学课件和书中所有实例源代码及其相关文件。通过学习本书,结合实例上机练习,一般能够在比较短的时间内掌握Qt 5应用技术。本书既可作为Qt 5的学习和参考用书,也可作为大学教材或Qt 5培训用书。
recommend-type

grpcio-1.46.3-cp37-cp37m-musllinux_1_1_i686.whl

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

大学生毕业答辨ppt免费模板【不要积分】下载可编辑可用(138).zip

大学生毕业答辨ppt免费模板【不要积分】下载可编辑可用(138).zip
recommend-type

Eclipse的C/C++自动补全插件org.eclipse.cdt.ui-7.3.100.202111091601

Eclipse的C/C++自动补全插件,制作参考:https://blog.csdn.net/kingfox/article/details/104121203?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-1-104121203-blog-117118786.235%5Ev43%5Epc_blog_bottom_relevance_base1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-1-104121203-blog-117118786.235%5Ev43%5Epc_blog_bottom_relevance_base1&utm_relevant_index=2
recommend-type

大学生毕业答辨ppt免费模板【不要积分】下载可编辑可用(137).zip

大学生毕业答辨ppt免费模板【不要积分】下载可编辑可用(137).zip
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://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

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