您的位置:首页 > 其它

1.5 从标准输入读命令并执行

2014-07-15 09:17 323 查看
proc/shell1.c

#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
char    buf[MAXLINE];    /* from apue.h */
pid_t    pid;
int        status;
printf("%% ");    /* print prompt (printf requires %% to print %) */
while (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = 0; /* replace newline with null */
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) {        /* child */
execlp(buf, buf, (char *)0);
err_ret("couldn't execute: %s", buf);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: