C++执行执行的 bash 脚本随机停止

C++ exec executed bash scripts stops randomly

本文关键字:执行 随机 bash C++ 脚本      更新时间:2023-10-16

我正在通过execvp执行一个bash脚本,但脚本中途停止执行。

看看我的代码:

int main()
{
    char* params[2];
    //First Parameter has to be the executable path
    params[0] = (char*) ::malloc(sizeof(char) * 40);
    ::strcpy(params[0], "/home/test.sh");
    //execv needs an null pointer as last argument
    params[1] = NULL;
    //Execute target executable
    ::execvp(params[0], params);
    //Only if ::exec() returns: output error
    std::cout << "Exec Failed!";
    exit(1);
}

我使用以下 bash 脚本进行测试:

#!/bin/bash -vx
echo "1" >> /home/out.txt
echo "2" >> /home/out.txt
echo "3" >> /home/out.txt
echo "4" >> /home/out.txt
echo "5" >> /home/out.txt
exit 0

大多数情况下,脚本甚至不执行,这意味着没有创建文件或没有将任何内容写入现有文件。Somtimes,但是脚本部分甚至全部执行,这意味着文本文件包含

1

为止

1
2
3
4
5

但是,无论 bash 脚本内部发生什么情况,应用程序总是以错误代码 0 退出。

为什么会这样?

如果我手动执行 bash 脚本,则每次到达脚本末尾时一切正常。因此,我认为它必须与我的 execvp 调用而不是 bash 脚本做一些事情。

我正在运行,因此在带有 debian 335 的 beaglebone 黑色系统 (am8.6) 上测试了该程序。

这是我

为使这个程序工作所做的:

注意:我用 C 重写了它

建议的 C 代码:

#include <stdio.h>   // perror()
#include <stdlib.h>  // exit()
#include <string.h>  // strcpy()
#include <unistd.h>  // execvp()

int main( void )
{
    char* params[2];
    //First Parameter has to be the executable path
    params[0] = "/home/rkwill/rtest.sh";
    //execv needs an null pointer as last argument
    params[1] = NULL;
    //Execute target executable
    execvp(params[0], params);
    perror( "execvp failed" );
    exit(1);
}

然后,在我的用户目录中:/home/rkwill/

touch rtest.sh

然后编辑"rtest.sh"以包含:

#!/bin/bash -vx
# generate file if not already in existence
touch /home/rkwill/out.txt
echo "1" >> /home/rkwill/out.txt
echo "2" >> /home/rkwill/out.txt
echo "3" >> /home/rkwill/out.txt
echo "4" >> /home/rkwill/out.txt
echo "5" >> /home/rkwill/out.txt
exit 0

然后使 bash 脚本可执行

chmod 777 rtest.sh

注意:我使用了目录/home/rkwill,因为我没有在/home 目录中写入的权限。

我第一次运行程序时,生成的"out.txt文件包含

1
2
3
4
5

每次连续运行都会将上述输出的重复附加到"out.txt