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
原文地址:https://www.cnblogs.com/myidea/p/4997136.html