linux——system的使用

这篇文章介绍了C语言中的system函数,它用于创建子进程执行给定的命令。当系统调用/bin/sh执行命令失败时,system函数返回127,其他错误返回-1。文中提供了示例代码展示了如何使用system调用执行命令,如改变数据配置文件和运行ps命令。通过对比execl函数,强调了system函数的便捷性。
摘要由CSDN通过智能技术生成

system函数api的使用

#include <stdlib.h>

int system(const char *command);

返回值:

        成功,则返回进程的状态值;不能执行时,返回127;失败返回-1;

分析源码:

#include
#include
#include
#include

int system(const char * cmdstring)
{
  pid_t pid;
  int status;

  if(cmdstring == NULL){
      
      return (1);
  }


  if((pid = fork())<0){

        status = -1;
  }
  else if(pid == 0){
    execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
    -exit(127); //子进程正常执行则不会执行此语句
    }
  else{
        while(waitpid(pid, &status, 0) < 0){
          if(errno != EINTER){
            status = -1;
            break;
          }
        }
    }
    return status;
}

可以看出,system是建立子进程来运行execl(system是封装后的execl函数)

如果system()在调用/bin/sh时失败则返回127,其他失败原因返回
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值