错误命令示例:
nohup java -jar -Dspring.profiles.active=prod -Xms102400m -Xmx102400m dzjzzz-service.jar & >> out.log 2>&1 &
正确写法:
去掉 >>out.log 前面的 & , 这个&可以换为1, 1>>out.log 和 >>out.log 是同样的作用,都是将标准输出重定向到out.log中
修正后为: nohup java -jar -Dspring.profiles.active=prod -Xms102400m -Xmx102400m dzjzzz-service.jar >> out.log 2>&1 &
以上表示将标准输出和标准错误都重定向到out.log文件中, 如果需要将标准错误输出到另一个文件中,可以写作:
nohup java -jar -Dspring.profiles.active=prod -Xms102400m -Xmx102400m dzjzzz-service.jar >> out.log 2>out_err.log &
测试样本:
ha.cpp -> ha.out
#include <unistd.h>
#include <string.h>
#include <string>
using namespace std;
#ifdef __WINDOWS__
#define _POPEN _popen
#define _PCLOSE _pclose
#else
#define _POPEN popen // Flawfinder: ignore
#define _PCLOSE pclose
#endif
static int ExeCmd(const char *pszCmd, char *strRetTmp, int maxLen)
{
char buffer[512] = {0};
FILE* pipe = _POPEN(pszCmd, "r");
if ( !pipe ){
return -1;
}
/* while( !feof(pipe) ){
if(fgets(buffer, 512, pipe)){
printf("aaa[%s]\n", buffer);
strncat(strRetTmp, buffer, maxLen);
}
}
*/
_PCLOSE(pipe);
return 0;
}
int main()
{
string cmd = """ + string("/home/test/sh_test.sh") + """;
char out[4096] = {0};
int ret = ExeCmd(cmd.data(), out, 4096);
printf("ret=%d\n", ret);
return 0;
}
main.cpp -> a.out
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main()
{
printf("hellow word\n");
while (1)
{
int t = time(0);
printf("hello, t= [%d]\n", t);
fflush(stdout);
sleep(1);
}
return 0;
}
sh_test.sh
#!/bin/bash
nohup ./a.out >> out.log 2>&1 &
#below is good
#nohup ./a.out &
#
#nohup ./a.out >> out.log 2>&1 &
#nohup ./a.out 1>>out.log 2>&1 &
echo "`date` xszzzz001 " >> test.txt
执行 ./ha.out
最上面那种错误写法,会导致./ha.out后不会结束,sh_test.sh脚本也没有退出。
附:
可以尝试一下 Linux Shell 的重定向。在 shell 脚本中,默认情况下,总是有三个文件处于打开状态,标准输入(键盘输入)、标准输出(输出到屏幕)、标准错误(也是输出到屏幕),它们分别对应的文件描述符是 0,1,2 。
> 默认为标准输出重定向,与 1> 相同,一般来说, "1> " 通常可以省略成 " > ";
2>&1 意思是把 标准错误输出 重定向到 标准输出;
&>file 意思是把标准输出 和 标准错误输出 都重定向到文件 file 中;
例如:
sh run.sh 1>out.txt 2>out.err,意思是把 run.sh 执行程序的标准输出保存到 out.txt 文件,把标准错误输出保存到 out.err 文件。
sh run.sh 1>output.txt 2>&1,意思是把 run.sh 执行程序的标准输出和标准错误输出都保存到 output.txt 同一个文件。