C++执行执行的 bash 脚本随机停止
C++ exec executed bash scripts stops randomly
我正在通过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
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++,系统无法执行指定的程序
- 为什么 Serial.println(<char[]>);返回随机字符?
- 使用C++中的模板和运算符重载执行矩阵运算
- 字符串-C++后显示的随机字符
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- GCC:随机构建导致执行期间分段错误
- 为什么变量的打印地址在每次执行时都会打印随机值,即使它是 C 中的逻辑地址?
- 我的控制台正在打印随机单词以及没有执行正确的数学运算
- 在标准输出中执行打印会导致数组中随机分配值
- 从本地工作,但在执行之间的随机端口上没有收到任何内容
- 执行随机开关函数的QT方式是什么连续两次使用相同情况的方法
- C++执行执行的 bash 脚本随机停止
- 我如何在 c++ 中执行随机结果,如下所示的代码
- 执行随机for循环并每次保存随机值
- 对 C++ 中的数组执行随机排列
- c++随机数生成器:如何在每次执行时使数字随机
- 游戏有时不会执行随机选择的策略