zoukankan      html  css  js  c++  java
  • system函数

    system函数

    • 它一个和操作系统紧密相关的函数,用户可以使用它在自己的程序中调用系统提供的各种命令

    • 执行系统的命令行,其实也是调用程序创建一个进程来实现的。实际上,system函数的实现正是通过调用fork、exec、waitpid函数来完成的。system函数原型如下:

        #include <stdlib.h>
        int system (const char *cmdstring);
      
    • 由于system在其实现中调用了fork、exec、waitpid,因此有三种可能的返回值:

        (1)如果fork失败或者waitpid返回除EINTR之外的出错,则system返回-1,而且errno中设置了错误类型
        (2)如果exec失败(表示不能执行shell),则其返回值如同shell执行了exit(127)一样,即返回值为127
        (3)否则所有三个函数(fork、exec和waitpid)都成功,并且system的返回值是shell的终止状态
      
    • system函数的使用时很方便的。

      system()调用fork()产生子进程,由子进程来调用/bin/sh-c cmdstring来执行参数cmdstring字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD信号会被暂时搁置,SIGINT和SIGQUIT信号则会被忽略

    一个关于system函数调用的例子,cmd_system.c:

    #include <stdlib.h>
    #include <stdio.h>
    int main(void)
    {
            int status;
            if((status = system(NULL)) < 0)
            {
                    printf("system error!
    ");
                    exit(0);
            }
            printf("exit status = %d
    ",status);
            if((status = system("date")) < 0)
            {
                    printf("system error!
    ");
                    exit(0);
            }
            printf("exit status = %d
    ",status);
            if((status = system("invalidcommand")) < 0)
            {
                    printf("system error!
    ");
                    exit(0);
            }
            printf("exit status = %d
    ",status);
            if((status = system("who;exit 44")) < 0)
            {
                    printf("system error!
    ");
                    exit(0);
            }
            printf("exit status = %d
    ",status);
            return 0;
    }
    
    
    
    运行结果:
    
    hyx@hyx-virtual-machine:~/test$ ./cmd_system
    exit status = 1
    2015年 11月 26日 星期四 10:24:08 CST
    exit status = 0
    sh: 1: invalidcommand: not found
    exit status = 32512
    hyx      :0           2015-11-25 23:21 (:0)
    hyx      pts/0        2015-11-25 23:22 (:0)
    exit status = 11264
  • 相关阅读:
    linux解释器、内建和外建命令
    linux文件cat/tac/more/less/head/tail/find/vimdiff
    zk和eureka的区别(CAP原则)
    Hystrix断路器中的服务熔断与服务降级
    windows 查看端口被占用,解除占用
    JS中操作JSON总结
    Ajax请求($.ajax()为例)中data属性传参数的形式
    通过 Ajax 发送 PUT、DELETE 请求的两种实现方式
    feignclient发送get请求,传递参数为对象
    Spring Boot 和 Spring Cloud Feign调用服务及传递参数踩坑记录
  • 原文地址:https://www.cnblogs.com/myidea/p/4997136.html
Copyright © 2011-2022 走看看