bushmills bushmills - 1 year ago 145
Linux Question

Creating tar.gz-archive from c++ program does not work

I use the following code snippet for creating a

-archive in an extensive measurement software. After collecting some data in several files I want to archive and compress them for later use.
Everything works fine when I start the program from the shell, all the data is collected and archived correctly.

However the program should start automatically after system start of an embedded Linux system. When it's started via a script in
, no data files are archived/compressed, even though I get the return value
. Furthermore, the tar.gz-file is created, but it's empty.
Everything else is working fine.

Can anyone please explain, what I have to do in this special case of an automatic start?

int returnValue = -1;
std::string jobString = RESULT_PATH;
jobString += "/";
jobString += lastJobString;
std::string jobFiles = lastJobString + "*.*";

std::string cmd = "tar cvf - ";
cmd += jobFiles;
cmd += " | gzip > ";
cmd += jobString;
cmd += ".tar.gz";

std::cout << "archiving and compressing " << jobFiles << ": " << cmd << std::flush << std::endl;

returnValue = system(cmd.c_str());

std::cout << "archiving and compressing finished. Code: " << returnValue << std::flush << std::endl;

I know that there are several librariers, like
, etc. which to use is not as lazy as firing a system command, but I would like to know why this does not work for my case.

Furthermore, the version of
in my busy box does not support option

Answer Source

I finally found a solution for my problem and maybe for all the cases when a system command is called by a daemon:

The trick is to create a new shell by the command sh and change the current directory before the tar-function is called:

std::string cmd = "sh -c \" cd ";
cmd += sourceDir;
cmd+= " && tar cvf - ";
cmd += jobFiles;
cmd += " | gzip > ";
cmd += jobString;
cmd += ".tar.gz";

returnValue = system(cmd.c_str());

Maybe this will help other users heading to the same problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download