一个简单的模拟shell的程序
来源:互联网 发布:公司网址和域名是什么 编辑:程序博客网 时间:2024/05/21 05:19
#include<stdio.h>#include<sys/stat.h>#include<unistd.h>#include<sys/wait.h>#include<string.h>#include<stdlib.h>#define MAXLINE 1024int main(){ char buf[MAXLINE]; pid_t pid; int status; printf("%%"); while( fgets(buf, MAXLINE, stdin) != NULL ) { if(buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0; if( (pid = fork()) < 0) { printf("fork error\n"); return; } else if(pid == 0) { execlp(buf, buf, (char *)0); printf("couldn't execute: %s\n", buf); return; } //pid = waitpid(pid, &status, 0); if( (pid = waitpid(pid, &status, 0)) < 0) { printf("waitpid error\n"); exit(0); } else { printf("finish status: %d\n", pid); } printf("%%"); } return 0;}
子进程调用execlp函数执行从输入得到的命令(不能含有空格的命令),fork和execlp的组合是某些操作系统所称的产生一个新进程.
子进程调用execlp执行新文件,而父进程希望子进程终止,用waitpid实现,参数pid为要等待的进程.其返回值为pid进程的终止状态(status变量)
运行结果:
ustcqi@ubuntu:~/workplace/linux/APUE/Demo1$ ./fork
%date
2012年 11月 21日 星期三 16:14:19 CST
finish status: 7058
%ls
fork fork.c fork.c~ getPID getPID.c getPID.c~
finish status: 7059
%pwd
/home/ustcqi/workplace/linux/APUE/Demo1
finish status: 7060
%dir
fork fork.c fork.c~ getPID getPID.c getPID.c~
finish status: 7061
%ustcqi@ubuntu:~/workplace/linux/APUE/Demo1$ gedit fork.c
ustcqi@ubuntu:~/workplace/linux/APUE/Demo1$
- 一个简单的模拟shell的程序
- 一个简单的shell程序
- 一个简单的模拟车场的程序
- 一个简单 的Shell 显示程序
- 一个简单的auth shell程序
- 一个最简单的shell程序
- shell学习笔记(2) 一个简单的shell脚本程序
- linux系统-shell编程-一个简单的shell程序
- 【Linux】shell的简单模拟
- 简单的shell程序
- 一个简单的shell
- 一个简单的shell
- 一个模拟简单的物品掉落的程序
- 一个模拟简单的物品掉落的程序
- 模拟一个简单的基于tcp的远程关机程序
- AutoIT模拟实现一个简单的供销存的程序
- 一个简单的shell脚本编写的GUI程序
- 自己动手写一个简单的Shell之二:运行程序
- 迷宫程序(3)
- 庖丁解牛TLD(二)——初始化工作(为算法的准备) .
- php中socket的使用
- android Camera模块分析
- 查看mysql数据库连接数、并发数相关信息
- 一个简单的模拟shell的程序
- occi编程遇到的问题:oracle::occi::Environment * __cdecl oracle::occi::Environment::createEnvironmenT
- HTML5如何改写创新与移动开发的游戏规则
- asp
- jQuery改变form表单的action,并进行提交
- gentoo安装过程
- System Server进程启动过程源码分析
- 庖丁解牛TLD(三)——算法初始化 .
- Ext4 简单的treepanel