How to include a string variable (char *) in the "system" command - linux

char * S = "hello"; // suppose it is correctly distributed correctly

I want to use S in the instructions below, when S will be considered as a string with the value "hello".

("grep S searchtext.txt> result.txt");

How to do it?

+6
c linux grep
source share
3 answers

In simple C, you traditionally use snprintf () to format the command line into a buffer:

char buf[1024]; snprintf(buf, sizeof(buf), "grep '%s' searchtext.txt > result.txt", S); system(buf); 

Of course, for security reasons, you should never do this if S comes from an external source, such as a file, a database, or the user himself. This can lead to shell code injection .

+1
source share

All in all, a very bad idea to use a system like this. system runs the command through the shell, which means that the line passed to system obeys all shell extensions, command extensions, special interpretation of characters, etc.

If you insist on using system , you should clear your line first. The easiest way to do this:

 char *tmp = malloc(4*strlen(S)+3); tmp[0] = '\''; for (i=0,j=1; tmp[j]=S[i]; i++, j++) if (S[i]=='\'') tmp[++j]='\\', tmp[++j]='\'', tmp[++j]='\''; tmp[j++] = '\''; tmp[j++] = 0; if (snprintf(cmd, sizeof cmd, "foo %s ...", tmp) >= sizeof cmd) goto error; system(cmd); 

This code selects the whole string S and replaces any embedded single quotes with '\'' . Please note that I also checked command line truncation in case this could lead to the execution of dangerous commands.

A better alternative would be to completely abandon system and execute your own fork and exec to get around the shell. Then there is no command line for interpretation; you have full control over the arguments ( *argv[] array) that are passed to the external program.

+8
source share

Well, there is a system primitive - execl, execp. So you can do it execl("ls", "-la", NULL) basically.

0
source share

All Articles