我试图制作一个程序,该程序使用exec
调用ls
和grep
系统调用。具体而言,我必须执行ls > tmp; grep -c pattern < tmp
以计算满足该模式的文件数量。正如你所看到的,我将ls的内容保存在tmp文件中,然后我想用grep来计算这些文件。使用execl获取grep值
我们来看看pattern = txt
。我想要的东西,如下面的代码:
char *a = "ls > tmp";
char *b = " -c ";
char *fin = " < tmp";
char *comanda;
if((comanda = malloc(strlen(pattern)+strlen(pattern)+1)) != NULL){
comanda[0] = '\0'; // ensures the memory is an empty string
strcat(comanda,b);
strcat(comanda, pattern);
strcat(comanda,fin);
} else {
return -1;
}
ret = execl("/bin/sh","sh","-c",a,NULL);
ret = execl("/bin/sh","sh","-c",comanda, NULL);
但它让我看到以下错误:ls: cannot access > tmp: No such file or directory
。所以我不知道如何得到grep
的值,因为execl
函数没有返回值,所以我怎样才能达到grep
的值呢?
您需要在()'和'叉创建一个子进程运行'execl'。 'execl()'用你运行的程序替换当前进程,它只会在尝试加载程序时出错。 – Barmar
这是我的实际观点,在一个子进程中,我将使用'execl',但无论如何,我得到的错误是:'ls:无法访问> tmp:没有这样的文件或目录' –
我不能再现那个错误,除非我改变它到'char * a =“ls'> tmp'”;' – Barmar