Linux函数system

Linux函数system

与exec的区别
1、system()和exec()都可以执行进程外的命令,system是在原进程上开辟了一个新的进程,但是exec是用新进程(命令)覆盖了原有的进程。
2、system()和exec()都有能产生返回值,system的返回值并不影响原有进程,但是exec的返回值影响了原进程。

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);
       //返回值见下文

因为system在其实现中调用了fork、exec和waitpid,因此有3种返回值。
(1) fork失败或者waitpid返回除EINTR之外出错,则system返回-1,并且设置errno以指示错误类型。
(2) 如果exec失败(表示不能执行shell),则其返回值如同shell执行了exit(127)一样。
(3) 否则所以3个函数(fork、exec、和waitpid)都成功,那么system的返回值是shell的终止状态,其格式可以参考waitpid。

实例:
我们先演示通过下面代码(change.c)来更改文件(TEST.config)数据:
在这里插入图片描述

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
        int  fdsrc;
        char *readbuf = NULL;

        if(argc != 2){
                printf("param error\ni");
                exit(-1);
        }

        fdsrc = open(argv[1],O_RDWR);

        int size = lseek(fdsrc,0,SEEK_END);
        lseek(fdsrc,0,SEEK_SET);

        readbuf = (char *)malloc(sizeof(size)+8);
        int n_read = read(fdsrc,readbuf,size);

        char *p = strstr(readbuf,"LENG=");

        if(p == NULL){
                printf("not found\n");
                exit(-1);
        }

        p=p+strlen("LENG=");
        *p='5';

        lseek(fdsrc,0,SEEK_SET);
        int n_write = write(fdsrc,readbuf,strlen(readbuf));

        close(fdsrc);
        return 0;
}

编译运行结果如下:LENG已被改为5.
在这里插入图片描述
下面用system来对TEST.config进行更改:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>

int main()
{
        pid_t pid;

        int data = 0;

        while(1){
                printf("please input a data\n");
                scanf("%d",&data);
                if(data==1){
                        pid=fork();
                        if(pid>0){
                                wait(NULL);
                        }
                        if(pid==0){
                        //      execl("./change","change","TEST.config",NULL);
                                system("./change TEST.config");
                        }
                }else{
                        printf("wait...\n");
                }
        }
        return 0;
}

在这里插入图片描述
在system参数直接写为“./change TEST.config”

实例2:
简单一点来掩饰:

#include <stdlib.h>
#include <stdio.h>

int main()
{
        printf("before system\n");
        system("ps -l");
        printf("after system\n");

        return 0;
}

直接把system的参数改为“ps -l”。结果如下:
在这里插入图片描述
调用函数system,开辟新进程,运行完新进程后接着运行下面程序(printf(“atter system\n”))。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值