[英]How to translate 'system()' call to 'fork() + execl()' when dealing with awk command?
1) the following system call works fine: 1)以下系统调用可以正常工作:
#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: 2)但如果我使用fork + execl替换上述系统:
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
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; 您的
system()
命令中的引号由shell处理; they're not passed to awk. 他们没有传递给awk。 As you're calling awk directly here, you need to omit the quotes.
当您直接在此处致电awk时,您需要省略引号。
That leads to the second problem: The shell is responsible for expanding environment variables like $PRI
. 这导致了第二个问题:Shell负责扩展环境变量,例如
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.