我正在通过 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
大多数时候脚本甚至不执行,这意味着没有文件正在创建或没有任何内容被写入现有文件。有时,脚本会部分或什至完全执行,这意味着文本文件包含
1
最多
1
2
3
4
5
但是无论 bash 脚本内部发生什么,应用程序总是以错误代码 0 退出。
为什么会这样?
如果我手动执行 bash 脚本,每次都可以正常运行到我的脚本末尾。因此,我认为它必须对我的 execvp 调用而不是 bash 脚本执行某些操作。
我正在运行,因此在带有 debian 8.6 的 beaglebone black 系统 (am335x) 上测试了该程序。
最佳答案
以下是我为使该程序正常运行所做的工作:
注意:我用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”
关于C++ exec 执行的 bash 脚本随机停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090448/