system函数-linux

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andrewgithub/article/details/82156477

函数介绍:

      system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

DESCRIPTION
       The  system()  library  function uses fork(2) to create a child process
       that executes the shell command specified in command using execl(3)  as
       follows:

           execl("/bin/sh", "sh", "-c", command, (char *) 0);

       system() returns after the command has been completed.

bash  -c  cal

bash -c binfile

andrew@andrew-Thurley:~$ bash -c cal
      八月 2018         
日 一 二 三 四 五 六  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31  

测试函数:

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


char *cmd1 = "/bin/date";

int main(void)
{

    system("clear");
    system(cmd1);
    return 0;
}


测试结果:

2018年 08月 28日 星期二 23:47:07 CST
andrew@andrew-Thurley:~/work/apue.2e$ 

编写自己的mysystem函数: bash -c binfilename

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


char *cmd1 = "date > s1.txt";
char *cmd2 = "date > s2.txt";

void mysystem(char *cmd);

int main(void)
{

    system("clear");
    system(cmd1);
    mysystem(cmd2);
    return 0;
}


void mysystem(char *cmd)
{
    pid_t   pid;
    if(pid = fork() < 0)
    {
        perror("fork error");
        exit(1);

    }
    else if(pid == 0)
    {
        if(execlp("/bin/bash", "bin/bash", "-c", cmd, NULL) < 0)
        {
            perror("execlp error");
            exit(1);
        }
    }
    wait(0);

}


猜你喜欢

转载自blog.csdn.net/andrewgithub/article/details/82156477