一个简单的模拟shell的程序
#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变量)
运行结果: