Linux知识之启动外部应用方法

    一般启动外部应用的方法有system,exec与popen。它们功能相似但使用上有所差别。

1. system

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

    (1) 此方法简单易用;

    (2) 但新进程会忽略SIGINT和SIGQUIT信号;

    (3) 返回值较多,容易与command的返回值混淆。

    (4) 示例:

#include <stdlib.h>

int main(int argc, char *argv[])
{
    system("ls");

    return 0;
}

2. exec族函数

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

    (1) 它会启用新进程,取代父进程(除调用exec失败外);

    (2) 可以使用父进程的上下文;

    (3) 示例:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    // 执行/bin目录下的ls, 第二个参数为程序名ls, 最后一个参数为占位必须NULL
    execl("/bin/ls", "ls", NULL);
    printf("============"); //execl执行成功则不会再执行该语句

    return 0;
}

3. popen管道

#include <stdio.h>
FILE * popen(const char *command, const char *type);

    (1) type为读写模式;

    (2) popen调用成功返回FILE指针,失败返回NULL;

    (3) 示例:

#include <stdio.h>

int main(int argc, char *argv[])
{
    FILE *fp = NULL;
    fp = popen("ls", "w");
    if(fp == NULL) {
        return -1;
    }
    pclose(fp);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/nicai_xiaoqinxi/article/details/85056363