简体   繁体   中英

Using bash system calls in C to write C that makes bash system calls

I'm playing around with a tiny app (in C) that, when run, creates a directory tree which it populates with files. It does this by using a series of lines of the form

system("echo \\"lump = \\" >> ./newdirectory/newfile.c");

This is working fine, except for when I try to have it write a line of C into the new file which itself contains a system("echo"); call.

Specifically,

system("echo \\"system(\\"echo hello world\\");\\" >> ./newdirectory/newfile.c");

gets written as

system(echo hello world);

Since you want the escape characters to appear as-is, you need to escape them too. Yes, you can escape escape characters. Something like:

"\\\""

This results in outputting a \\ followed by an " .

It is crazy play. But I think, right way of this crazyness is writing C function to escape string.

Internal string must be double escaped.

system("echo \"system(\\\"echo hello world\\\");\" >> ./newdirectory/newfile.c");

Othervise first C unescape literal string and shell get

echo "system("echo hello world");" >> ./newdirectory/newfile.c

It wrong quotes in echo not escaped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM