温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

system函数怎么用

发布时间:2021-10-21 13:49:34 来源:亿速云 阅读:309 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“system函数怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“system函数怎么用”这篇文章吧。

system函数是一个和操作系统紧密相关的函数,用户可以使用它在自己的程序中调用系统提供的各种命令。函数原型如下: 

  #include<stdlib.h>
  int system(const char *cmdstring);

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

    如果参数cmdstring是一个空指针NULL,则仅当命令处理程序可用时,system返回非0值,这一特征可以决定在一个给定的操作系统上是否支持system函数,当返回0时,表示system无效。

例如:

#include<stdlib.h>
#include<stdio.h>
void main()
{
        int status;
        if((status=system(NULL))<0)
        {
                printf("system error.\n");
                exit(0);
        }
        printf("exit status=%d\n",status);
        if((status=system("date"))<0)
        {
                printf("system error.\n");
                exit(0);
        }
        printf("exit status=%d\n",status);
        if((status=system("invalidcommand"))<0)
        {
                printf("system error.\n");
                exit(0);
        }
        printf("exit status=%d\n",status);
        if((status=system("who;exit 44"))<0)
        {
                printf("system error.\n");
                exit(0);
        }
        printf("exit status=%d\n",status);
}

运行结果:

exit status=1
Wed Mar 22 09:20:45 CST 2017
exit status=0
sh: invalidcommand: command not found
exit status=32512
root     pts/0        2017-03-22 09:07 (124.152.7.168)
exit status=11264

在第一次调用system是参数为空指针,返回结果1,说明在该系统下system是可用的。

第二次调用system时,参数为date,执行成功。

第三次调用system时,参数为一个非法字符串,system返回值为shell的终止状态32512(命令出错)。

第四次调用system时,使用who命令显示登录到系统的当前用户情况,exit是退出当前的shell,可以看到system返回112674,成功执行。

以上是“system函数怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI