dejunl
dejunl

Reputation: 57

How to translate 'system()' call to 'fork() + execl()' when dealing with awk command?

1) the following system call works fine:

#define LOG_FILE_PATH "/tmp/logfile"
system("awk -v PRI=\"$PRI\" '/^<'$PRI'>/' "LOG_FILE_PATH);

2) but if I use fork+execl to replace the above system:

pid = fork();
if (pid == 0) {
    execl("/usr/bin/awk", "awk", "-v", "PRI=\"$PRI\"", "'/^<'$PRI'>/'", LOG_FILE_PATH, (char *)0);
} else {
    /* parent */
}

I got the error message:

awk: cmd. line:1: Unexpected token

Upvotes: 0

Views: 359

Answers (1)

melpomene
melpomene

Reputation: 85777

That should be something like:

execl("/usr/bin/awk", "awk", "-v", "PRI=???", "/^<???>/", LOG_FILE_PATH, (char *)0);

The quotes in your system() command are processed by the shell; they're not passed to awk. As you're calling awk directly here, you need to omit the quotes.

That leads to the second problem: The shell is responsible for expanding environment variables like $PRI. You'll need to do this manually, maybe like this:

char tmp1[123], tmp2[123];
snprintf(tmp1, sizeof tmp1, "PRI=%s", getenv("PRI"));
snprintf(tmp2, sizeof tmp2, "/^<%s>/", getenv("PRI"));
execl("/usr/bin/awk", "awk", "-v", tmp1, tmp2, LOG_FILE_PATH, (char *)0);

Upvotes: 1

Related Questions