linux 练习三 fork函数和exev函数族
2017-11-29 12:46
253 查看
编写两个不同的可执行程序,名称分别为a和b,b为a的子进程。 在a程序中调用open函数打开a.txt文件。 在b程序不可以调用open或者fopen,只允许调用read函数来实现读取a.txt文件。 (a程序中可以使用 fork与execve函数创建子进程)。 a.c //fork函数 父子进程 共享(复制)文件描述符 #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc,char * argv[]) { pid_t pid; int fd; if(argc < 2) { printf("please input 2 para\n"); exit(1); } printf("the process pid=%d\n",getpid()); fd = open(argv[1],O_RDONLY,0); if(fd < 0) { perror("open"); exit(1); } pid = fork(); if(pid < 0) { perror("fork"); exit(1); } else if(0 == pid) { char buf[10]; sleep(1); sprintf(buf,"%d",fd); printf("now is in child process,pid=%d,it's parent pid=%d\n",getpid(),getppid()); if(execl("./b.o","b.o",buf,NULL)<0) { perror("execl"); exit(1); } } else { if(close(fd) < 0) { perror("close"); } printf("close file over\n"); printf("wait for child process over\n"); pid = waitpid(pid,NULL,0); printf("child process pid =%d over\n",pid); } } b.c #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> int main(int argc, char* argv[]) { int fd; int i; char buf[100]; int readnum; if(argc < 2) { printf("b process please input 2 para\n"); exit(1); } printf("now is in b process\n"); for(i = 0;i<argc;i++) { printf("argv[%d]=%s\n",i,argv[i]); } fd = atoi(argv[1]); if(fd < 3) { printf("b process please input correct fd\n"); exit(1); } do{ bzero(buf,sizeof(buf)); readnum = read(fd,buf,sizeof(buf)); printf("%s",buf); }while(readnum == sizeof(buf)); printf("\n"); }
相关文章推荐
- 【linux练习】基础作业一
- linux学习-练习1
- linux下小练习及答案(2)
- 【原创】TCP Socket 简单练习 --- 新进程辅助通信 分类: Linux --- 应用程序设计 2014-12-23 10:27 64人阅读 评论(0) 收藏
- Linux 第二天: (07月22日) 练习和作业
- linux脚本练习-1
- Linux_C练习:判断一个字符串是不是另一个字符串的子串;(比如"ab"是"aabcd"的子串)
- Linux下shell脚本中信号捕获和函数练习脚本之ping一个网段
- linux运维实战练习案例-2015年12月20日-12月31日(第一次)
- linux命令练习与答案
- Linux操作练习00:VitualBox下实现文件Windows到Linux的文件共享
- linux练习-unit1
- linux运维实战练习-2015年8月30日课程作业
- Linux基础练习
- linux之grep命令和正则表达式练习
- linux命令练习:mount fdisk swap dd创建本地回环设备
- linux下练习 c++ 普通容器的使用
- linux C 练习一
- linux小练习1
- Linux编程练习 --多线程3--mutex