zoukankan      html  css  js  c++  java
  • 1.8 从标准输入读命令并执行2

    int execlp(const char *file, const char *arg, ...);
    函数说明:
    execlp()会从PATH 环境变量所指的目录中查找符合参数file的文件名,找到后便执行该文件,然后将第二个以后的参数当做该文件的argv[0]、argv[1]……,最后一个参数必须用空指针(NULL)作结束。如果用常数0来表示一个空指针,则必须将它强制转换为一个字符指针,否则将它解释为整形参数,如果一个整形数的长度与char * 的长度不同,那么exec函数的实际参数就将出错。如果函数调用成功,进程自己的执行代码就会变成加载程序的代码,execlp()后边的代码也就不会执行了。
    返回值:
    如果执行成功则函数不会返回,执行失败则直接返回-1,失败原因存于errno 中。
     

    proc/shell2.c

     1 #include "apue.h"
     2 #include <sys/wait.h>
     3 static void    sig_int(int);        /* our signal-catching function */
     4 int
     5 main(void)
     6 {
     7     char    buf[MAXLINE];    /* from apue.h */
     8     pid_t    pid;
     9     int        status;
    10     if (signal(SIGINT, sig_int) == SIG_ERR)
    11         err_sys("signal error");
    12     printf("%% ");    /* print prompt (printf requires %% to print %) */
    13     while (fgets(buf, MAXLINE, stdin) != NULL) {
    14         if (buf[strlen(buf) - 1] == '
    ')
    15             buf[strlen(buf) - 1] = 0; /* replace newline with null */
    16         if ((pid = fork()) < 0) {
    17             err_sys("fork error");
    18         } else if (pid == 0) {        /* child */
    19             execlp(buf, buf, (char *)0);
    20             err_ret("couldn't execute: %s", buf);
    21             exit(127);
    22         }
    23         /* parent */
    24         if ((pid = waitpid(pid, &status, 0)) < 0)
    25             err_sys("waitpid error");
    26         printf("%% ");
    27     }
    28     exit(0);
    29 }
    30 void
    31 sig_int(int signo)
    32 {
    33     printf("interrupt
    %% ");
    34 }
  • 相关阅读:
    php函数每日学习二十个(第二天)
    php函数每日学习二十个
    php代码效率小常识
    出差回来继续学习更新
    开博第一篇文章
    “类视图”和“对象浏览器”图标
    ASP.NET页面回车键触发Button按钮事件问题
    设置TextBox控件的TextMode属性
    C# 获取系统时间及时间格式
    ASP.NET 常用状态(信息)保存方式
  • 原文地址:https://www.cnblogs.com/paullam/p/3844022.html
Copyright © 2011-2022 走看看