如何翻译“系统()调用'fork()的+ execl的()'与awk命令打交道时? [英] How to translate 'system()' call to 'fork() + execl()' when dealing with awk command?
本文介绍了如何翻译“系统()调用'fork()的+ execl的()'与awk命令打交道时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
1)以下的系统调用正常工作:
的#define LOG_FILE_PATH的/ tmp /日志文件
系统(AWK -v PRI = \\$ PRI \\'/ ^<'$ PRI'> /'LOG_FILE_PATH);
2),但如果我使用fork + execl的,以取代上述系统:
PID =叉();
如果(PID == 0){
execl的(/ USR /斌/ AWK,AWK,-v,PRI = \\$ PRI \\,/ ^&下;'$ PRI'&GT /',LOG_FILE_PATH,(的char *)0);
}其他{
/ *母公司* /
}
我得到的错误消息:
AWK:CMD。行:1:意外的令牌
解决方案
这应该是这样的:
EXECL(在/ usr /斌/ AWK,AWK,-v,PRI = ???,/ ^< ???> /,LOG_FILE_PATH,(字符*)0);
在的行情系统()
命令由shell处理;他们没有传递给AWK。正如你在这里可以直接调用awk中,你需要省略引号。
这引出了第二个问题:外壳是负责拓展如 $ PRI
环境变量。你需要手动做到这一点,也许是这样的:
字符TMP1 [123],TMP2 [123];
的snprintf(TMP1,sizeof的TMP1,PRI =%S,GETENV(PRI));
的snprintf(TMP2,sizeof的TMP2,/ ^<%S> /,GETENV(PRI));
EXECL(在/ usr /斌/ AWK,AWK,-v,TMP1,TMP2,LOG_FILE_PATH,(字符*)0);
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
解决方案
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);
这篇关于如何翻译“系统()调用'fork()的+ execl的()'与awk命令打交道时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文