execvp函数详解_如何在C / C ++中使用execvp()函数

execvp函数详解

In this article, we’ll take a look at using the execvp() function in C / C++.

在本文中,我们将介绍如何在C / C ++中使用execvp()函数。

In UNIX, the execvp() function is very useful if you want to run another program using our C program.

在UNIX中,如果要使用我们的C程序运行另一个程序,execvp()函数将非常有用。

NOTE: This function is applicable only to UNIX based Operating Systems. It doesn’t work on Windows

注意 :此功能仅适用于基于UNIX的操作系统。 在Windows上不起作用

Let’s take a look at executing UNIX commands from our program, using illustrative examples!

让我们使用示例说明一下从程序中执行UNIX命令的方法!



execvp()的基本语法 (Basic Syntax of execvp())

This function takes in the name of the UNIX command to run, as the first argument.

该函数将要运行的UNIX命令的名称作为第一个参数。

This is there in the <unistd.h> header file, so we must include it in our program.

该文件位于<unistd.h>头文件中,因此我们必须将其包含在程序中。


#include <unistd.h>

int execvp(const char* command, char* argv[]);

Here, we refer to a “command” as any binary executable file that is a part of the PATH environment variable. So, if you want to run custom programs, make sure that you add it to your PATH variable!

在这里,我们将“命令”称为PATH环境变量一部分的任何二进制可执行文件。 因此,如果要运行自定义程序,请确保将其添加到PATH变量中!

The second argument (argv) represents the list of arguments to command. This is an array of char* strings.

第二个参数( argv )表示command的参数列表。 这是一个char*字符串数组。

Here, argv contains the complete command, along with it’s arguments.

在这里, argv包含完整的命令及其参数。

For example, the below array follows the format of argv.

例如,下面的数组遵循argv的格式。


char* argument_list[] = {"ls", "-l", NULL}; // NULL terminated array of char* strings

// Ok! Will execute the command "ls -l"
execvp("ls", argument_list);

This array MUST be NULL terminated, i.e, the last element of argv must be a NULL pointer.

该数组必须NULL终止,即argv的最后一个元素必须是NULL指针。

现在我们的C程序会怎样? (What happens to our C program now?)

This function will give the control of the current process (C program) to the command. So, the C program is instantly replaced with the actual command.

该功能将控制当前过程(C程序)到命令。 因此,C程序立即被实际命令替换。

So, anything that comes after execvp() will NOT execute, since our program is taken over completely!

因此,由于我们的程序已被完全接管,因此execvp()之后的所有内容均将execvp()执行!

However, if the command fails for some reason, execvp() will return -1.

但是,如果命令由于某种原因失败,则execvp()将返回-1。

So, whenever you use execvp(), if you want to maintain your C program, you generally use fork() to first spawn a new process, and then use execvp() on that new process.

因此,无论何时使用execvp() ,如果要维护C程序,通常都可以使用fork()首先产生一个新进程,然后在该新进程上使用execvp()

This is called the “fork-exec” model, and is the standard practice for running multiple processes using C.

这称为“ fork-exec”模型,并且是使用C运行多个进程的标准实践。

Let’s now look at some examples, to understand this function better. We’ll also be using fork() along with execvp(), so that we can still have our C program with us!

现在让我们看一些示例,以更好地理解此功能。 我们还将使用fork()execvp() ,以便我们仍然可以使用C程序!

在C / C ++中使用execvp()–一些示例 (Using execvp() in C / C++ – Some Examples)

If you want to see what exactly happens if you try to use execvp() without spawning a new process using fork(). the below program shows this.

如果您想查看如果尝试使用execvp()而没有使用fork()产生新进程时发生的情况,将会发生什么。 下面的程序显示了这一点。

We’ll be executing “ls -l” from our C program.

我们将在C程序中执行“ ls -l”。

Notice that the printf() statement after execvp() is NOT executed, since the other process has taken control!

注意, execvp()之后的printf()语句未执行,因为另一个进程已经控制了!


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

int main() {
    char* command = "ls";
    char* argument_list[] = {"ls", "-l", NULL};

    printf("Before calling execvp()\n");

    // Calling the execvp() system call
    int status_code = execvp(command, argument_list);

    if (status_code == -1) {
        printf("Process did not terminate correctly\n");
        exit(1);
    }

    printf("This line will not be printed if execvp() runs correctly\n");

    return 0;
}

Output

输出量


Before calling execvp()
total 3
-rwxrwxrwx 1 user user 22088 May 30 16:37 a.out
-rwxrwxrwx 1 user user 16760 May 30 16:37 sample
-rw-rw-rw- 1 user user  1020 May 30 16:37 sample.c

As you can see, the part after execvp() does not execute at all, since “ls -l” took control of our process!

如您所见, execvp()之后的部分根本不执行,因为“ ls -l”控制了我们的过程!

Let’s re-write the same example, but let’s enclose the execvp() system call inside another process, using fork().

让我们重写相同的示例,但是使用fork()execvp()系统调用包含在另一个进程中。

Let’s see what happens now.

让我们看看现在会发生什么。


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

int main() {
    char* command = "ls";
    char* argument_list[] = {"ls", "-l", NULL};

    printf("Before calling execvp()\n");

    printf("Creating another process using fork()...\n");

    if (fork() == 0) {
        // Newly spawned child Process. This will be taken over by "ls -l"
        int status_code = execvp(command, argument_list);

        printf("ls -l has taken control of this child process. This won't execute unless it terminates abnormally!\n");

        if (status_code == -1) {
            printf("Terminated Incorrectly\n");
            return 1;
        }
    }
    else {
        // Old Parent process. The C program will come here
        printf("This line will be printed\n");
    }

    return 0;
}

Output

输出量


Before calling execvp()
Creating another process using fork()...
This line will be printed
user@shell:$ total 3
-rwxrwxrwx 1 user user 22088 May 30 16:37 a.out
-rwxrwxrwx 1 user user 16760 May 30 16:37 sample
-rw-rw-rw- 1 user user  1020 May 30 16:37 sample.c

If you’re in a shell, the output may look weird, but that’s because multiple processes ran in parallel! Both the outputs were indeed printed, so we’ve been able to resolve our problem.

如果您在shell中,输出看起来可能很奇怪,但这是因为多个进程并行运行! 这两个输出确实都已打印,因此我们已经能够解决问题。



结论 (Conclusion)

We learned about using the execvp() function in C / C++, to execute other programs from our C program. However, note that this will give the other program complete control of our process.

我们了解了如何在C / C ++中使用execvp()函数从C程序执行其他程序。 但是,请注意,这将使其他程序完全控制我们的过程。

Due to this, we need to enclose this under another process, using the fork() system call. Hopefully, this made sense to you, and you were able to run other programs, while still being able to have control over your C program!

因此,我们需要使用fork()系统调用将其包含在另一个进程中。 希望这对您有意义,您可以运行其他程序,同时仍然可以控制您的C程序!

参考资料 (References)



翻译自: https://www.journaldev.com/40793/execvp-function-c-plus-plus

execvp函数详解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值