一、进程与信号之exec函数system函数

exec函数:

子进程调用exec函数执行另一个程序,exec函数进程完全由新程序代替,替换原有程序正文,数据,堆,栈段

#include <unistd.h>
extern char **environ;
int execl(const char *path,const char *arg, ...);
int execlp(const char *file,  const char *arg, ...);
int execle(const char *path,const char *arg, ..., char * const envp[]);
int execv(const char *path,char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *file, char *const argv[], char *const envp[]);

exec函数出错返回-1,成功不返回

execve是系统函数,其他都是库函数

 

system函数

#include <stdlib.h>

int system(const char *command)

返回:成功返回命令状态,出错返回-1
功能:简化exec函数使用

system函数内部构建一个子进程,由子进程调用exec函数
等同于/bin/bash -c "cmd" 或者 exec("bash","-c","cmd")
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

char *cmd1="/bin/date";

int main(void)
{
    system("clear");
    system(cmd1);
    
    return 0;
}

system函数源码

#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
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;

}

 

转载于:https://www.cnblogs.com/peixiguang/p/5831812.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值