首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Linux/Unix C, 基础学习《Unix环境高级编程》 从标准输入读下令并执行

2012-11-21 
Linux/Unix C, 基础学习《Unix环境高级编程》 从标准输入读命令并执行《Unix环境高级编程第二版》 程序块1.7in

Linux/Unix C, 基础学习《Unix环境高级编程》 从标准输入读命令并执行
《Unix环境高级编程第二版》 程序块1.7


include "apue.h"#include <sys/wait.h>#include "lib/error.c"intmain(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);}~    


gcc -o fig1.7_ fig1.7.c
./fig1.7_

输入输出结果:

%% ls
test.c test2.c test.o

热点排行