1
當我嘗試像這樣擴展grep時,它不起作用。爲什麼擴展grep不起作用?
const char *grep[] = { "grep", "-E", "'JOBS|COMPIZ'" };
如果我這樣做,只是沒有單引號然後它一個字符串。爲什麼?爲什麼我不能像上面那樣構建擴展grep的參數?以下只有一個字符串正在工作。
const char *grep[] = { "grep", "-E", "JOBS" };
我的程序應該做printenv | sort | grep <parameter-list> | less
,如果沒有參數主要然後程序應該做的printenv | sort | less
。我已經實現了後者的功能,現在我需要實現參數列表的grep,但我似乎無法在C代碼中進行擴展grep。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct command
{
const char **argv;
};
int
spawn_proc (int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork()) == 0)
{
if (in != 0)
{
dup2 (in, 0);
close (in);
}
if (out != 1)
{
dup2 (out, 1);
close (out);
}
return execvp (cmd->argv [0], (char * const *)cmd->argv);
}
return pid;
}
int
fork_pipes (int n, struct command *cmd)
{
int i;
pid_t pid;
int in, fd [2];
/* The first process should get its input from the original file descriptor 0. */
in = 0;
/* Note the loop bound, we spawn here all, but the last stage of the pipeline. */
for (i = 0; i < n - 1; ++i)
{
pipe (fd);
/* f [1] is the write end of the pipe, we carry `in` from the prev iteration. */
spawn_proc (in, fd [1], cmd + i);
/* No need for the write and of the pipe, the child will write here. */
close (fd [1]);
/* Keep the read end of the pipe, the next child will read from there. */
in = fd [0];
}
/* Last stage of the pipeline - set stdin be the read end of the previous pipe
and output to the original file descriptor 1. */
if (in != 0)
dup2 (in, 0);
/* Execute the last stage with the current process. */
return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}
int
main (int argc, char ** argv)
{
printf("in main...");
int i;
if (argc == 1) {
const char *printenv[] = { "printenv", 0};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {sort}, {less} };
return fork_pipes (3, cmd);
}
if (argc > 1) {
/*char *tmp = argv[1];
sprintf(tmp, "%s%s", "'", tmp);*/
for(i=1; i<argc-1; i++)
{
/* tmp = "%s%s%s", tmp, "\\|", argv[i];
printf("tmp:%s", tmp);
sprintf(tmp, "%s%s%s", tmp, "|", argv[i]);
sprintf(tmp, "%s%s", tmp, "'");*/
}
const char *printenv[] = { "printenv", 0};
const char *grep[] = { "grep", "-E", "JOB" };
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
return fork_pipes (4, cmd);
}
}
提供給'exec'系列函數的'argv'數組需要被'NULL'指針終止。 – 2015-04-03 16:14:27
@JoachimPileborg謝謝!這是有效的:'const char * grep [] = {「grep」,「-E」,「JOB | COMPIZ \ 0」};' – 2015-04-03 16:22:30
這也不是很正確,它應該是'const char * grep [] = {「grep」,「-E」,「JOB | COMPIZ」,NULL};' – 2015-04-03 16:25:20